Regular Expressions aka Regex are expressions that define a search pattern. They are widely used for validation purposes, like email validation, url validation, phone number validation and so on. Forming Regex: A regex is written between two forward slashes (/) delimiters. These delimiters are essential only for certain Regex engines (JS,PHP.). Regular Expressions - Cheat Sheet This cheat sheet is intended to be a quick reminder for the main concepts involved in using regular expressions and assumes you already understand their usage. If you are new to regular expressions we strongly suggest you work through the Regular Expressions tutorial from the beginning.
h.o matches hoo, h2o, h/o, etc.
Use to search for these special characters:[ ^ $ . | ? * + ( ) { }
ring? matches ring?
(quiet) matches (quiet)
c:windows matches c:windows
regex engine is 'eager', stops comparing
as soon as 1st alternative matches
[DS] means not digit OR whitespace, both match
[^ds] disallow digit AND whitespace
colou?r match color or colour
* 0 or more[BW]ill[ieamy's]* match Bill, Willy, William's etc.
+ 1 or more[a-zA-Z]+ match 1 or more letters
{n} require n occurrencesd{3}-d{2}-d{4} match a SSN
{n,} require n or more[a-zA-Z]{2,} 2 or more letters
{n,m} require n - m[a-z]w{1,7} match a UW NetID
(see modifiers)
bring word starts with 'ring', ex ringtone
ringb word ends with 'ring', ex spring
b9b match single digit 9, not 19, 91, 99, etc..
b[a-zA-Z]{6}b match 6-letter words
B NOT word edgeBringB match springs and wringer
^ start of string $ end of string^d*$ entire string must be digits
^[a-zA-Z]{4,20}$ string must have 4-20 letters
^[A-Z] string must begin with capital letter
[.!?')]$ string must end with terminal puncutation
$_(GET|POST|REQUEST|COOKIE|SESSION|SERVER)[.+]
'id' matches, but 'b' fails after atomic group,
parser doesn't backtrack into group to retry 'identity'
(?=ingb)
match warbling, string, fishing, ... (?!w+ingb)
w+b words NOT ending in 'ing'(?<=bpre)
.*?b match pretend, present, prefix, ...(?<!pre)
w*?b words NOT starting with 'pre' (lookbehind needs 3 chars, w{3}, to compare w/'pre')
(?<!ing)
b match words NOT ending in 'ing'The lookahead prevents matches on PRE, PARAM, and PROGRESS tags by only allowing more characters in the opening tag if P is followed by whitespace. Otherwise, '>' must follow '<p'.
Find: (.*)(?= .*n) (.*)n
Repl: 2, 1n
— insert 2nd capture (lastname) in front of first capture (all preceding names/initials)
Find: (.*?), (.*?)n
— group 1 gets everything up to ', ' — group 2 gets everything after ', '
Repl: 2 1n
(?=(sometext))
the inner () captures the lookahead
This would NOT work: ((?=sometext))
Because lookaround groups are zero-width, the outer () capture nothing.
re?d
vs r(?=e)d
re?d
— match an 'r', an optional 'e', then 'd' — matches red or rdr(?=e)d
— match 'r' (IF FOLLOWED BY 'e') then see if 'd' comes after 'r' (?<=h1)
or (?<=w{4})
look behind for 'h1' or for 4 'word' characters. (?<=w+)
look behind for 1 or more word characters. Lookaround groups define the context for a match. Here, we're seeking .* ie., 0 or more characters.
A positive lookbehind group (?<= . . . )
preceeds. A positive lookahead group (?= . . . )
follows.
These set the boundaries of the match this way:
In other words, advance along string until an opening HTML tag preceeds. Match chars until its closing HTML tag follows.
The tags themselves are not matched, only the text between them.
To span multiple lines, use the (?s) modifier. (?s)(?<=<cite>).*(?=</cite>)
Match <cite> tag contents, regardless of line breaks.
As in example above, the first group (w+)
captures the presumed tag name, then an optional space and other characters ?.*?
allow for attributes before the closing >.
class='red'
and class='blue red green'
etc. Here, the first group captures only the tag name. The tag's potential attributes are outside the group.
(NB: This markup <a> would end the match early. Doesn't matter here. Subsequent < pulls match to closing tag. But if you attempted to match only the opening tag, it might be truncated in rare cases.)
The IF condition can be set by a backreference (as here) or by a lookaround group.
For a quick overview: http://www.codeproject.com/KB/dotnet/regextutorial.aspx.
For a good tutorial: http://www.regular-expressions.info.
Something to bear in mind is that regex is actually a declarative programming language like prolog : your regex is a set of rules which the regex interpreter tries to match against a string. During this matching, the interpreter will assume certain things, and continue assuming them until it comes up against a failure to match, which then causes it to backtrack. Regex assumes 'greedy matching' unless explicitly told not to, which can cause a lot of backtracking. A general rule of thumb is that the more backtracking, the slower the matching process.
It is therefore vital, if you are trying to optimise your program to run quickly (and if you can't do without regex), to optimise your regexes to match quickly.
I recommend the use of a tool such as 'The Regex Coach' to debug your regex strings.
http://weitz.de/files/regex-coach.exe (Windows installer) http://weitz.de/files/regex-coach.tgz (Linux tar archive)
One comment about 5.2.x and the pcre.backtrack_limit:
Note that this setting wasn't present under previous PHP releases and the behaviour (or limit) under those releases was, in practise, higher so all these PCRE functions were able to 'capture' longer strings.
With the arrival of the setting, defaulting to 100000 (less than 100K), you won't be able to match/capture strings over that size using, for example 'ungreedy' modifiers.
So, in a lot of situations, you'll need to raise that (very small IMO) limit.
The worst part is that PHP simply won't match/capture those strings over pcre.backtrack_limit and will it be 100% silent about that (I think that throwing some NOTICE/WARNING if raised could help a lot to developers).
There is a lot of people suffering this changed behaviour from I've read on forums, bugs and so on).
Hope this note helps, ciao :-)
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE):
http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/