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)
Alternation is usually left-to-right. /(Sam|Samwise)/ will match 'Sam' in 'Samwise'. So put longer alternatives first, like /(Samwise|Sam)/.
11
2,042
Reminder: * means zero or more, + means one or more, ? means zero or one.
6
1,964
\W matches any non-word character, anything \w doesn't match.
4
2,054
\w matches any 'word' character, i.e. letters, numbers, and underscore. Equivalent to [a-zA-Z0-9_]
8
2,367
\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,104
Matching dates is harder than it looks: leap years, month lengths, etc. Keep 'date-ish' regexes honest about what they validate.
10
2,017
Perl's special vars: $& (match), $` (pre-match), $' (post-match). Handy but can slow down regex in some Perl versions.
1
5
2,087
\d matches any digit. \D matches anything except a digit. 'Digit' can include more characters than you may expect when using Unicode.
7
1,999
\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,902
\s matches white space, i.e. space, tab, newline, etc. Example: /foot\s+ball/ matches 'foot ball' but not 'football'.
2
6
2,055
A common bug: forgetting to escape backslashes in replacement strings in languages that treat backslash as an escape.
1
1
7
1,819
$ anchors a regular expression at the end of a strings. Example: /end$/ matches strings ending in 'end'.
5
1,981
Portability tip: avoid \R, \h, \v, and other shorthand escapes unless you know your target engines support them.
4
1,981
In Python, backreferences in replacement use \1 or \g<1> or \g<name>. \g<...> avoids ambiguity like '\11'.
1
9
2,368
Using regular expressions to search genetic data sciencedirect.com/science/ar…
2
1,900