Ranges in character classes
A range inside a character class covers every character between two endpoints by code point: [a-z] lowercase ASCII letters, [0-9] digits, [0-9a-fA-F] hex digits, and several ranges can share one class. A numeric range such as 1 to 255 cannot be one range; it needs an alternation built per digit length.
Syntax
[a-z] [A-Z] [0-9] [a-zA-Z0-9] [0-9a-fA-F]Examples
"A7 b3 Z9 x".match(/[A-Z][0-9]/g)Result: ["A7", "Z9"]
/^[0-9a-fA-F]+$/.test("CAFE42")Result: true
"a-b".match(/[a\-z]/g)Result: ["a", "-"]
An escaped hyphen is literal; this class matches a, hyphen or z.
["0", "7", "42", "100", "101"].map(s => /^(?:[1-9]\d?|100)$/.test(s))Result: [false, true, true, true, false]
1 to 100: one or two digits without a leading zero, or exactly 100.
Common mistakes
- [a-Z] is invalid: Z (code 90) comes before a (code 97), so the range is out of order.
- [A-z] is valid but also includes the six characters between Z and a: [ \ ] ^ _ and the backtick.
- [1-31] does not mean 1 to 31; it means 1 to 3 or 1. Numeric ranges need alternation.
- An unescaped hyphen between two characters creates a range you did not intend; put it first, last, or escape it.
Practice Ranges in character classes
These drills check your answer on live data, free, no account needed.
- Ranges: a letter and two digitsThe whole line must match. Match one lowercase letter followed by exactly two digits, like a12.
- IPv4 addresses, 0 to 255The whole line must match. Match four numbers from 0 to 255 separated by dots. No leading zeros, so 01 is not allowed.
- Character class: gray or greyThe whole line must match. Match both spellings, gray and grey, and nothing else.
Questions
How do I match a number range in regex?
Split it by digit length: 0 to 255 is 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d. For anything more complex, match \d+ and compare the number in code.
Is [a-z] case-insensitive?
No. Use [a-zA-Z] or add the i flag, which makes [a-z] match uppercase letters too.
How do I match accented letters?
Ranges like [a-zà-ÿ] are fragile. Use \p{L} with the u flag in JavaScript to match any letter in any script.
Related
- Character classesWhat a character class matches, how ranges and negation work, what \d \w \s and their uppercase opposites mean, and what the dot does and does not match.
- Negated character classHow [^...] matches any character except the listed ones, stripping non-digits, grabbing quoted text, splitting on a delimiter, and how it differs from (?!).
- Regex for IPv4 addressA loose and a strict IPv4 regex, how the 0 to 255 alternation works, how to find IP addresses in log text, and the cheaper split-and-compare alternative.
- Alternation |How the pipe works, why ^cat|dog$ does not do what it looks like, how to group alternatives, and why option order matters when one is a prefix of another.