Regex Cheat Sheet


Character Legend Example Sample Match
\d One digit file_\d\d file_25
\w One "word character": letter, underscore or digit \w-\w\w\w A-b_1
\s One white space character (e.g.: a tab) ab\s\s\sc ab    c
\D One character that is not a digit \D\D\D ABC
\W One character that is not a word character \W\W\W\W\W *-+=)
\S One character that is not a space \S\S\S\S Yoyo


Quantifier Legend Example Sample Match
+ One or more Version \w-\w+ Version A-b1_1
{3} Exactly three times \D{3} ABC
{2,4} Two to four times \d{2,4} 156
{3,} Three or more times \w{3,} regex_tutorial
* Zero or more times A*B*C* AAACC
? Once or none plurals? plural


Character Legend Example Sample Match
\t Tab T\t\w{2} T     ab
\r Return character see below
\n New line character see below
\r\n New line in Windows AB\r\nCD AB
CD


Quantifier Legend Example Sample Match
+ The + (one or more) is "greedy" \d+ 12345
? Makes quantifiers "lazy" \d+? 1 in 12345
* The * (zero or more) is "greedy" A* AAA
? Makes quantifiers "lazy" A*? empty in AAA
{2,4} Two to four times, "greedy" \w{2,4} abcd
? Makes quantifiers "lazy" \w{2,4}? ab in abcd


Character Legend Example Sample Match
[stuff] One of the characters in the brackets [AEIOU] One uppercase vowel
- Range indicator [a-z] One lowercase letter
[stuff] One of the characters in the brackets [AB1-5w-z] One of either: A,B,1,2,3,4,5,w,x,y,z
[stuff] One of the characters in the brackets [A-Z]+ GREAT
[^x] One character that is not x [^a-z]{3} A1!
[\d\D] One character that is a digit or a non-digit [\d\D]+ Any characters, including new line


Anchor Legend Example Sample Match
^ Beginning of line (but means "not" inside [^brackets]) ^abc .* abc (line start)
$ End of line .*? the end$ this is the end
\A Beginning of string \Aabc[\d\D]* abc (string...
...start)
\Z End of string [\d\D]*the end\Z this is...
...the end
\b Word boundary Bob.*\bcat\b Bob ate the cat
\B Not a word boundary Bob.*\Bcat\B.* Bobcats


Character Legend Example Sample Match
[:alpha:] Letters [8[:alpha:]]+ WellDone88
[:alnum:] Letters and numbers alnum:{10} ABCDE12345
[:punct:] Punctuation marks + ?!.,:;


Modifier Legend Example Sample Match
(?i) Case-insensitive (?i)Monday monDAY
(?s) The dot (.) matches new line characters (\r\n) (?s)From A.*to Z From A
to Z
(?m) Treats the string as multiple lines, so that ^ and $ can match in several places (?m)1\r\n^2$\r\n^3$ 1
2
3
(?x) Comment mode (aka whitespace mode) (?x) # this is a
# comment
abc # write on multiple
# lines
[ ]d # spaces must be
# in brackets
abc d


Lookaround Legend Example Sample Match
(?= Positive lookahead (?=\d{10})\d{5} 01234 in 0123456789
(?<= Positive lookbehind (?<=\d)cat cat in 1cat
(?! Negative lookahead (?!theatre)the\w+ theme
(?<! Negative lookbehind \w{3}(?<!mon)ster Munster