JS: Regex Syntax. Character Class
Any character
[chars]-
Any character between the brackets.
console.log( "cat cet cit cot cut".match(/c[aou]t/g), ); // [ "cat", "cot", "cut" ]
Character range
[a-z]-
char range from a to z.
the range is determined by the Code Point.
// character range , a to z console.log( "Alice was.".match(/[a-z]+/g), ); // [ "lice", "was" ] // character range , greek α to ω console.log( "math Δ β ∂ ℝ.".match(/[α-ω]+/g), ); // [ "β" ] // demo using character class range by codepoint. // character range , emoji range. // regex must have flag v. console.log( "📺 and 🤡.".match(/[\u{1f300}-\u{1fad0}]/gv), ); // [ "📺", "🤡" ] range can be combined to have a union of ranges.
// combined character ranges , a to z and A to Z and 0 to 9 console.log( "M-a.73".match(/[a-zA-Z0-9]/g), ); // [ "M", "a", "7", "3" ] // character range , digits 0 to 9, a to f, A to F. with boundary. // this is like getting hexadecimal strings. console.log( "hsy3Z 1567 2a06a.".match(/\b[0-9a-fA-F]+\b/g), ); // [ "1567", "2a06a" ]
With char class escape
[character_class_escape]-
any character class escape, e.g.
\w→ word (include digits and hyphen)\d→ digits 0 to 9.\s→ whitespace.
and their negation
\W\D\S.note, we show that it is valid to have them inside square brackets, but if it is the only thing, it is not necessary to put it inside square bracket.
// demo, it is valid to have char class escape inside square brackets console.log( "a-y4_".match(/[\w]/g), ); // [ "a", "y", "4", "_" ]
Unions of any char and range and char class escape
[mixed]-
// a to g, 0 to 9 console.log( "ab-y42".match(/[a-g0-9]/g), ); // [ "a", "b", "4", "2" ] // a to g, 0 to 9, and y i j console.log( "ab-iz42".match(/[a-g0-9yij]/g), ); // [ "a", "b", "i", "4", "2" ] // match word class \w plus hyphen // when you have hyphen, best to put it in front, the avoid confusing with range syntax console.log( "ab-y42".match(/[-\w]/g), ); // [ "a", "b", "-", "y", "4", "2" ]
Negation
-
[^…] -
Any char that's not one of the character in the brackets.
Advanced
Note, the pattern [syntax] is extremely complicated.
we only documented the most common use-cases.
when the square bracket pattern
[syntax]
is used with flag u or flag v,
it has extended syntax, and the syntax is parsed in a more strict way.