Regular Expressions Cheat Sheet - 2021
bogotobogo.com site search:
Regular Expressions
Regular expressions (regexes or regex patterns) are made available through the re module.
Matching Characters
- [abc]
Matches any of the characters a, b, or c; this is the same as [a-c], which uses a range to express the same set of characters.
If we want to match only lowercase letters, our RE should be [a-z]. - [^5]
Matches any character except '5' - [^0-9]
Matches any non-digit character. This is equivalent to \D. - backslash, \
- \d
matches any decimal digit; this is equivalent to [0-9]. - \D
matches any non-digit character; this is equivalent to [^0-9] - \s
matches any whitespace character; this is equivalent to [ \t\n\r\f\v].
[\s,.] will match any whitespace character, or ',' or '.'. - \S
matches any non-whitespace character; this is equivalent to [^ \t\n\r\f\v] - \w
matches any alphanumeric character; this is equivalent to [a-zA-Z0-9_] - \W
matches any non-alphanumeric character; this is equivalent to [^a-zA-Z0-9_]
- \d
Repeating match
- *
The '*' metacharacter doesn’t match the literal character '*'. Rather, it specifies that the previous character can be matched zero or more times, instead of exactly once.
- ca*t
matches 'ct' (0 'a' characters), 'cat' (1 'a'), 'caaat' (3 'a' characters), and so forth. - a[bcd]*b
matches the letter 'a', zero or more letters from the class [bcd], and finally ends with a 'b'.
- ca*t
- +
matches one or more times. Note the difference between * and +
* matches zero or more times, so whatever’s being repeated may not be present at all, while + requires at least one occurrence.
- ca+t
matches 'cat' (1 'a'), 'caaat' (3 'a's), but won't match 'ct'.
- ca+t
- ?
matches either once or zero times
- home-?brew
matches either 'homebrew' or 'home-brew'.
- home-?brew
- {m,n}
there must be at least m repetitions, and at most n.
- a/{1,3}b
matches 'a/b', 'a//b', and 'a///b'. It won’t match 'ab', which has no slashes, or 'a////b', which has four.
- a/{1,3}b
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization