Is it only me? I am always scrambling to write regular expressions in one go and always have to look up on what all those symbols do. I am always looking for these stuffs online. Here you will find commonly used regular expression examples. Hope this list will help you all.

Regular Expression

Regular expression is used to describe a pattern of characters. It can match a part of string and can be used for advanced character matching and replacing. We can use preg_match function in PHP for comparing string with regular expression.

Meta characters

Meta characters are used to match specific type of character. Some examples of meta characters are listed below

\dany digit from 0 to 9
\wany character from a to z, A to Z and 0 to 9
\sany white space character (space, tab etc.)
^starts with
$ends with
*means zero or more
+means one or more
.match any single character be it letter, number, whitespace etc
\match meta character by escaping them
ipatterns are case sensitive. Adding i modifier after regular expression makes it case insensitive
[]square bracket are used to denote character sets. It matches one of any of the characters in the bracket
[ – ]hyphen specifies a range of characters eg: [0-9] … This matches a single digit between 0 and 9

Some examples of regular expressions

Regular ExpressionStringMatches?Remarks
/abc/abcYesmatches literal abc
/abc/abczxvYesString still contains abc
/abc/bcwzNoLooking for literal abc which is not present in string
/10:20/10:20:25Yes
/ab\d/ab12Yes\d matches number
/abc\d/ab12NoThere is no c
/\d\d/ab12Yes
/\w\s\d/ab 12Yes
/^abc/abcYes
/^abcxyz/abcxyzYes
/^abc/123abcNoDoesn’t start with abc
/abc$/123abcYes
/^abc$/abcYes
/^abc$/ abcxyzNo
/a*bc/abcYeslook for a repeated zero or more times
/a*bc/bcYes
/a+bc/bcNopattern is looking for at least one a
/a+bc/aaaabcYes
/ab.de/abcdeYes
/ab.de/ab4deYes
/ab.de/ab deYes
/ab.de/abdeNo
/abc.*/abcdefYes.* any number of any character
/abc.*/abcYes
/abc\./abc.Yes matches literal dot character
/abc/AbcNopattern are case sensitive
/abc/iAbcYesi modifier makes pattern case insensitive
/a[123]b/a2bYes
/a[123]b/ a3bYes
/a[123]b/ a4bNo
/a[123]+b/a123233bYes
/a[1-5]b/a2bYesMatches character between 1 and 5
/a[1-5]b/ a8bNo
/[a-z0-9 ]+/hello worldYes
/a[^123]b/a2bNo^ matches any one character except for the characters specified including ranges
/a[^123]b/ a4bYes
/[^a-z]+/helloNo
/[^a-z]+/ HELLOYes