Regular Expression (@RegexTip) header
Regular Expression (@RegexTip) profile picture

Learn to use regular expressions by following RegexTip. From @JohnDCook.

Joined November 2009
Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)Photo by Regular Expression (@RegexTip)
Parentheses and | denote options. Example: /(red|green|blue) truck/ matches 'red truck' or 'green truck' or 'blue truck'.
7
2,361
Regex to find strings that look like IPv4 addresses inside text: \b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b
2
1
18
2,384
Alternation is usually left-to-right. /(Sam|Samwise)/ will match 'Sam' in 'Samwise'. So put longer alternatives first, like /(Samwise|Sam)/.
13
2,262
Reminder: * means zero or more, + means one or more, ? means zero or one.
7
1,986
\W matches any non-word character, anything \w doesn't match.
4
2,065
\w matches any 'word' character, i.e. letters, numbers, and underscore. Equivalent to [a-zA-Z0-9_]
8
2,375
\w isn't just [A-Za-z0-9_]. In Unicode mode it includes many letters/digits. Use an ASCII flag if you need strict ASCII.
1
9
2,110
Matching dates is harder than it looks: leap years, month lengths, etc. Keep 'date-ish' regexes honest about what they validate.
10
2,021
Perl's special vars: $& (match), $` (pre-match), $' (post-match). Handy but can slow down regex in some Perl versions.
1
5
2,090
\d matches any digit. \D matches anything except a digit. 'Digit' can include more characters than you may expect when using Unicode.
7
2,012
\S matches anything but white space, i.e. \S is the opposite of \s. This is a common pattern with upper case vs lower case.
1
8
1,906
\s matches white space, i.e. space, tab, newline, etc. Example: /foot\s+ball/ matches 'foot ball' but not 'football'.
2
6
2,058
A common bug: forgetting to escape backslashes in replacement strings in languages that treat backslash as an escape.
1
1
7
1,821
$ anchors a regular expression at the end of a strings. Example: /end$/ matches strings ending in 'end'.
5
1,983
Portability tip: avoid \R, \h, \v, and other shorthand escapes unless you know your target engines support them.
4
1,983
In Python, backreferences in replacement use \1 or \g<1> or \g<name>. \g<...> avoids ambiguity like '\11'.
1
9
2,370