regular expressions cheat sheet v2

Anchors

Sample Patterns

^

Start of line +

([A-Za-z0-9-]+)

Letters, numbers and hyphens

End of line +

([^\s]+(?=\.(jpg|gif|png))\.\2)

jpg, gif or png image

\A

Start of string +


\Z

End of string +

$

\b

Word boundary +

\B

Not word boundary +

\<

Start of word

\>


End of word

Character Classes
\c

Control character

\S

Not white space

\s

White space

\d

Digit


\D

Not digit

\w

\W

\Oxxx

[:cntrl:]

[:graph:]
[:print:]

Lower case letters
Digits and letters
Digits

??


{3}

{3,}

{3,5}

{3,5}?

0 or 1, ungreedy +
Exactly 3 +

3 or more +
3, 4 or 5 +

3, 4 or 5, ungreedy +

Special Characters

Blank characters


\r

Carriage return +

Control characters
Printed characters

Printed characters and

Lookbehind assertion +

Note

?

1 or more, ungreedy +

Escape Character +


?

Quantifiers

0 or 1 +

underscore

?!= or ?]+)\>)

8 to 15 character string with at least one

Any character except

Upper case letters

[:xdigit:]

(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})


Valid hexadecimal colour code

.

[:upper:]

[:digit:]

((?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15})

Any number from 1 to 50 inclusive

0 or more +

POSIX Character Classes

[:alnum:]

(#?([A-Fa-f0-9]){3}(([A-Fa-f0-9]){3})?)


*

Octal character xxx

[:lower:]

(^[1-9]{1}$|^[1-4]{1}[0-9]{1}$|^50$)

Date (e.g. 21/3/2006)

Word

Not word

\xhh

(\d{1,2}\/\d{1,2}\/\d{4})

\n
\t


\v
\f

\a

[\b]
\e

\N{name}

New line +
Tab +

Vertical tab +

Named Character

"xyz" in /^(?:abc)(xyz)$/


Comment

Items marked + should work in most
regular expression implementations.

$+
$&
$_
$$

\n

Note

Upper case letter +

between A and Q +

Digit between 0 and 7 +
nth group/subpattern +

Ranges are inclusive.

Pattern Modifiers

Multiple lines

Escape

$1

Condition [if then else]

[0-7]

Letter between a and q +

m

Negative lookbehind +

$'

[A-Q]

Not a or b or c +

Backspace

nth non-passive group

$`

[a-q]

Range (a or b or c) +

Global match

$n

Condition [if then]

[^abc]

Passive Group +

g

Alarm

Negative lookahead +

Once-only Subexpression

[abc]

Group +

Form feed +

String Replacement (Backreferences)
$2

(...)

new line (\n) +

"xyz" in /^(abc(xyz))$/

i

Case-insensitive

s

Treat string as single line

x

Allow comments and

white space in pattern

e

Evaluate replacement

U

Ungreedy pattern

Metacharacters (must be escaped)

Before matched string

^

[

.

Last matched string

(

\

+

After matched string

Entire matched string
Entire input string
Literal "$"

$
)

<

{
|

>
Available free from
AddedBytes.com

*
?