Match One of Many Characters
Character class
Create a character class to match one occurrence inside a []
regexp
c[ae]l[ae]nd[ae]r
1
Range operator
Create a certain range using -
Match one of hexadecimal characters:
regexp
[a-fA-F0-9]
1
Reversed range like
[f-a]
are not valid
Negation operator
Negate a range using leading ^
Match Non-hexadecimal characters:
regexp
[^a-fA-F0-9]
1
Escape inside character class
There's four special characters may need to be escaped:
-
range operator^
negation operator[
and]
start and end of character class
For any character that are not one of above, is not required to be escaped:
regexp
[$()*+.?{|]
1
For ^
s not act as negation are not required to be escaped:
regexp
[a-f^A-F\^0-9]
1
Also for -
and [
/]
INFO
It's recommended to always escape metacharacters in character classes
Shorthand character classes
\d
matches any single digit, equivalent to[\d]
and[0-9]
\D
matches any character that is not a digit, equivalent to[^\d]
and[^0-9]
\w
matches any word character, equivalent to[a-zA-Z0-9_]
\W
matches any character that is not a word character, equivalent to[^\w]
\s
matches any whitespace character, like tabs, spaces, line breaks.\S
matches any character that is not a whitespace character
INFO
- In
.NET
,\w
matches not only[a-zA-Z0-9_]
, it also includes other letters like Cyrillic and Thai. \s
also matches whitespace characters in Unicode in.NET
andJavaScript