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)
Reminder: * means zero or more, + means one or more, ? means zero or one.
2
600
\W matches any non-word character, anything \w doesn't match.
4
1,999
\w matches any 'word' character, i.e. letters, numbers, and underscore. Equivalent to [a-zA-Z0-9_]
8
2,356
\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
8
2,098
Matching dates is harder than it looks: leap years, month lengths, etc. Keep 'date-ish' regexes honest about what they validate.
10
2,014
Perl's special vars: $& (match), $` (pre-match), $' (post-match). Handy but can slow down regex in some Perl versions.
1
5
2,084
\d matches any digit. \D matches anything except a digit. 'Digit' can include more characters than you may expect when using Unicode.
7
1,990
\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,900
\s matches white space, i.e. space, tab, newline, etc. Example: /foot\s+ball/ matches 'foot ball' but not 'football'.
2
6
2,052
A common bug: forgetting to escape backslashes in replacement strings in languages that treat backslash as an escape.
1
1
7
1,816
$ anchors a regular expression at the end of a strings. Example: /end$/ matches strings ending in 'end'.
5
1,978
Portability tip: avoid \R, \h, \v, and other shorthand escapes unless you know your target engines support them.
4
1,979
In Python, backreferences in replacement use \1 or \g<1> or \g<name>. \g<...> avoids ambiguity like '\11'.
1
9
2,366
Using regular expressions to search genetic data sciencedirect.com/science/ar…
2
1,898
Outside a character class, ^ means 'start at the beginning of a line'. Example: /^The/ matches lines that begin with 'The'.
3
11
2,178
\d is not always [0-9]. In Unicode-aware engines, \d may match non-ASCII digits. Use an ASCII mode/flag or [0-9] if you mean only 0-9.
1
2
15
2,770