Python Regex Basics and Usage Guide
Python Regex Basics and Usage Guide
regex
Python has a module implementing regular expression (re). The re module can be imported to
search for matching of pattern in string.
[Link]() scans the search string from left to right, and as soon as it locates a match for
<regex>, it stops scanning and returns the match.
1
12/03/24
Introduction to Python (Regular expression)
Literal characters: Characters as it is. It matches the first occurrence of the pattern character.
Case sensitive.
Metacharacters or special character: Certain characters are reserved for special use. These are
listed in the table.
Metacharacter Usage
[] Specify a character class or character set. [ap] – can match a or p
{} Matches explicit specified number of repetitions of the regex before
{}. 9{2} matches string containing substring ’99’
() Create groups
| Alteration. (mat|pat) will match mat or pat
+ Matches one or more repetitions of the regex before it.
* Matches zero or more repetitions of the regex preceding it. a*, will
match one more occurrence starting with a
2
12/03/24
Introduction to Python (Regular expression)
Metacharacter Usage
? - It matches zero or one repetition
- It specifies the non-greedy versions of *, +, and ?
- Creates a named group,
- Lookahead/lookbehind assertions
. Matches any character except new line
\ Escape a matacharacter for matching; special character class;
grouping backreference.
<> Named group
\w Matches any alphanumeric word character
\W Opposite of \w. Matches non-word character
\d Matches any decimal character
\D Is opposite of \d. Matches any character that is non-digit
\s Matches any whitespace character
\S Matches any non-whitespace character
3
12/03/24
Introduction to Python (Regular expression)
Metacharacter Usage
^ - Anchors matches the position before the first character in string.
^d to ‘def’ matches d
- Complements a character.
$ Anchors matches the last position in the string f$ applied to ‘def’
\b Anchors matches to a word boundary
\B Anchor matches to a non-word boundary
4
12/03/24
Introduction to Python (Regular expression)
Capturing groups:
(:?regex)
In this case the groups are not be considered for group counting.
5
12/03/24
Introduction to Python (Regular expression)
Named capturing group:
Lookahead and lookbehind assertion determines the success or failure of a regex match based
on the presence of (text/regex) ahead(right) or behind(left) of the matching regex.
Lookahead:
regexA(?=regexB) The match will return only if regexA is followed by
regexB
Lookbehind:
(?<=regexB)regexA The match will return only if regexA is followed by
regexB
7
12/03/24