Skip to content

Regular Expressions Cheat Sheet

Basic matching

Expression Matches
ab absent, flab, drabness
a|b a, b
t(i|o)ck tick, tock
apple|banana apple, banana

Quantifiers

a* zero one or more a
a? zero or one a
a+ one or more a
a{4} aaaa
a{4,6} aaaa, aaaaa, aaaaaa
a{4,} four or more a
a{,4} zero to four a
(ab)* zero, one or more ab 

similarly for (ab)? and (ab)+, and (ab){4,6}

Start and end

^a any expression starting a
a$ any expression ending a

Characters

. any character
In general, any character preceded by a backslash gives that character as a literal, so
\. .
\$ $
You will need this convention to use any of the following characters as literals: 

\ $ ^ . ( ) [ ] | * ? + { }

The following sequences beginning with backslash have special significance as characters, and some as character classes
40 ascii character with octal code 040
\x20 ascii character with hex code 20
\cA control-A
\u0020 Unicode character with hex code 0020
\a ascii 7 (bell)
\t ascii 9 (tab)
\r ascii 13 (carriage return)
\w ascii 11 (vertical tab)
\n ascii 10 (newline)
\e ascii 27 (escape)

Character classes

[abc] any of a, b, c
[a-z] any of the characters a-z
[a-z0-9] any of the characters a-z or 0-9
[^abc] anything other than a, b or c 

similarly for [^a-z], [^a-z0-9]

\p{name} the named unicode character class
\P{name} anything other than \p{name}

Words and spaces

\w any alphanumeric
\W anything other than \w
\s any white space
\S anything other than \S
\d any numeric character
\D anything other than \d
\b matches a word break, which is an “invisible” character at the start or end of a word. Can be used rather like $ or ^ but on a word basis.
ing\b starting, stopping, helping out
\bstart starting, started, somewhat startled
[\b] ascii 8 (backspace)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: