JS: Regex Syntax. Character Class
work in progressCharacter class square brackets
Note, the pattern [syntax] is extremely complicated.
Here we just document the most common use-cases.
when the square bracket pattern
[syntax]
is used with flag u or flag v,
it has extended syntax.
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.
// character range console.log( "Alice was.".match(/[a-z]+/g), ); // [ "lice", "was" ] // character range , digits. console.log( "there are 3 cats.".match(/[0-9]+/g), ); // [ "3" ]
With char class escape
contains_character_class_escape-
word class in brackets
// using word class \w inside square brackets (redundant) console.log( "ab-y42".match(/[\w]/g), ); // [ "a", "b", "y", "4", "2" ]
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.