A website of the Watkiss Online Group. Also see the First Aid Quiz Website.

Penguin Image

Programming - perl regular expression quick reference guide

This is a quick reference guide to some of the most common special characters used in regular expression matching. This is based on perl regular expressions, which are also used in php using preg_match and some other programming languages / applications.

Character matches

\s White space [\t\n\r\f]
\S Not white space [^\t\n\r\f]
\d Digit [0-9]
\D Not digit [^0-9]
\w Word character [a-zA-Z_0-9]
\W Nonword character e.g. [^a-zA-Z_0-9]

Quantifiers


* 0 or more
*? 0 or more, not greedy
+ 1 or more
+? 1 or more, not gready
? 0 or 1
?? 0 or 1, not gready
{x} Exactly x times
{x,y} Between x and y times
{x,y} Between x and y times, not gready
^ At the beginning of the string
$ At the end of the string

Special characters

\ Escape chracter
\n New line
\r Carriage return
\t Tab

String replacement references

$n Bracketed group (n is which group) – non passive
$` Before matched string
$' After matched string
$+ Last matched string
$& Entire matched string
$_ Entire input string
$$ Literal $

Ranges

. Any character except \n
(a|b) a or b
(...) Group
(?:...) Passive group
[abc] a, b or c
[^abc] not a or b or c
[a-c] Any letter from a to c
[A-C] Any upper case letter A to C
[0-5] Any digit 0 to 5

Pattern modifiers

g Global match (multiple)
i Case-insensitive
m Multiple lines
s Treat string as single line
U Un-greedy pattern

Metacharacters (must be escaped)

^ [ . $ { * ( ) \ + | ? < >

Previous Introduction to regular expressions
Introduction to regular expressions
Next Guide to the Raspberry Pi
Guide to the Raspberry Pi