Python Regular Expressions
A regular expression is a special sequence of characters that helps you conveniently check whether a string matches a certain pattern.
Python added the re module starting from version 1.5, which provides Perl-style regular expression patterns.
The re module gives the Python language full regular expression functionality.
The compile function generates a regular expression object based on a pattern string and optional flags parameters. This object has a series of methods for regular expression matching and replacement.
The re module also provides functions with exactly the same functionality as these methods; these functions use a pattern string as their first argument.
This chapter mainly introduces the commonly used regular expression processing functions in Python.
The re.match function
re.match tries to match a pattern from the start of the string; if the match is not successful at the start position, match() returns none.
Function syntax:
re.match(pattern, string, flags=0)
Function parameter description:
| Parameters | Description |
|---|---|
| pattern | The regular expression to match |
| string | The string to be matched. |
| flags | Flags that control how the regular expression is matched, such as case sensitivity and multi-line matching. See:Regular expression modifiers - optional flags |
If the match is successful, the re.match method returns a match object; otherwise it returns None.
We can use the group(num) or groups() match object functions to get the matched expression.
| Match object methods | Description |
|---|---|
| group(num=0) | The string of the whole matched expression; group() can take several group numbers at once, in which case it returns a tuple containing the values of those groups. |
| groups() | Returns a tuple containing all the subgroup strings, from 1 up to the number of subgroups contained. |
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
re
(
re
.
match
(
'
www
'
,
'
www.runoob.com
'
)
.
span
(
)
)
Match at the starting position
(
re
.
match
(
'
com
'
,
'
www.runoob.com
'
)
)
Do not match at the starting position
The above example produces the following output:
(0, 3)
None
Example
#!/usr/bin/python
import
re
line
=
"
Cats are smarter than dogs
"
matchObj
=
re
.
match
(
r
'
(.) are (.?) .*
'
,
line
,
re
.
M
|
re
.
I
)
if
matchObj
:
"
matchObj.group() :
"
,
matchObj
.
group
(
)
"
matchObj.group(1) :
"
,
matchObj
.
group
(
1
)
"
matchObj.group(2) :
"
,
matchObj
.
group
(
2
)
else
:
"
No match!!
"
The above example produces the following result:
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
The re.search method
re.search scans the whole string and returns the first successful match.
Function syntax:
re.search(pattern, string, flags=0)
Function parameter description:
| Parameters | Description |
|---|---|
| pattern | The regular expression to match |
| string | The string to be matched. |
| flags | Flags, used to control the way regular expressions match, such as whether to be case-sensitive, multi-line matching, and so on. |
On a successful match the re.search method returns a match object, otherwise it returns None.
We can use the group(num) or groups() match object functions to get the matched expression.
| Match object methods | Description |
|---|---|
| group(num=0) | The string of the whole matched expression; group() can take several group numbers at once, in which case it returns a tuple containing the values of those groups. |
| groups() | Returns a tuple containing all the subgroup strings, from 1 up to the number of subgroups contained. |
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
re
(
re
.
search
(
'
www
'
,
'
www.runoob.com
'
)
.
span
(
)
)
Match at the starting position
(
re
.
search
(
'
com
'
,
'
www.runoob.com
'
)
.
span
(
)
)
Do not match at the starting position
The above example produces the following output:
(0, 3)
(11, 14)
Example
#!/usr/bin/python
import
re
line
=
"
Cats are smarter than dogs
"
;
searchObj
=
re
.
search
(
r
'
(.) are (.?) .*
'
,
line
,
re
.
M
|
re
.
I
)
if
searchObj
:
"
searchObj.group() :
"
,
searchObj
.
group
(
)
"
searchObj.group(1) :
"
,
searchObj
.
group
(
1
)
"
searchObj.group(2) :
"
,
searchObj
.
group
(
2
)
else
:
"
Nothing found!!
"
The above example produces the following result:
searchObj.group() : Cats are smarter than dogs
searchObj.group(1) : Cats
searchObj.group(2) : smarter
The difference between re.match and re.search
re.match only matches the beginning of the string; if the beginning of the string does not match the regular expression, the match fails and the function returns None. re.search, on the other hand, matches the entire string until it finds a match.
Example
#!/usr/bin/python
import
re
line
=
"
Cats are smarter than dogs
"
;
matchObj
=
re
.
match
(
r
'
dogs
'
,
line
,
re
.
M
|
re
.
I
)
if
matchObj
:
"
match --> matchObj.group() :
"
,
matchObj
.
group
(
)
else
:
"
No match!!
"
matchObj
=
re
.
search
(
r
'
dogs
'
,
line
,
re
.
M
|
re
.
I
)
if
matchObj
:
"
search --> searchObj.group() :
"
,
matchObj
.
group
(
)
else
:
"
No match!!
"
The above example produces the following result:
No match!!
search --> searchObj.group() : dogs
Search and replace
Python's re module provides re.sub for replacing matches in a string.
Syntax:
re.sub(pattern, repl, string, count=0, flags=0)
Parameters:
- pattern : the pattern string in the regular expression.
- repl : the replacement string, which can also be a function.
- string : the original string to be searched and replaced.
- count : the maximum number of replacements after a pattern match; the default 0 means replace all matches.
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
re
phone
=
"
2004-959-559 # This is a foreign phone number
"
Remove Python comments from the string
num
=
re
.
sub
(
r
'
#.*$
'
,
"
"
,
phone
)
"
The phone number is:
"
,
num
Remove the non-digit (-) characters from the string
num
=
re
.
sub
(
r
'
\D
'
,
"
"
,
phone
)
"
The phone number is :
"
,
num
The above example produces the following result:
电话号码是: 2004-959-559
电话号码是 : 2004959559
The repl parameter is a function
The following example multiplies the matched numbers in a string by 2:
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
re
Multiply the matched number by 2
def
double
(
matched
)
:
value
=
int
(
matched
.
group
(
'
value
'
)
)
return
str
(
value
2
)
s
=
'
A23G4HFD567
'
(
re
.
sub
(
'
(?P
\d
+)
'
,
double
,
s
)
)
The execution output is:
A46G8HFD1134
re.compile function
The compile function is used to compile a regular expression, generating a regular expression (Pattern) object that can be used by functions such as match(), search(), and findall.
The syntax is:
re.compile(pattern[, flags])
Parameters:
-
pattern : A regular expression in the form of a string
-
flags : Optional, indicating the matching mode, such as ignoring case, multi-line mode, etc. The specific parameters are:
Example
Example
import
re
pattern
=
re
.
compile
(
r
'
\d
'
)
Used to match at least one digit
m
=
pattern
.
match
(
'
one12twothree34four
'
)
Search the head, no match
m
None
m
=
pattern
.
match
(
'
one12twothree34four
'
,
2
,
10
)
Start matching from the position of 'e', no match
m
None
m
=
pattern
.
match
(
'
one12twothree34four
'
,
3
,
10
)
Start matching from the position of '1', an exact match
m
Returns a Match object
<
_sre
.
SRE_Match
object
at
0
x10a42aac0
m
.
group
(
0
)
0 can be omitted
'
12
'
m
.
start
(
0
)
0 can be omitted
3
m
.
end
(
0
)
0 can be omitted
5
m
.
span
(
0
)
0 can be omitted
(
3
,
5
)
Above, when a match succeeds a Match object is returned, in which:
group([group1, …])method is used to get one or more group-matched strings; to get the whole matched substring you can directly usegroup()orgroup(0);start([group])method is used to get the starting position of a group-matched substring in the whole string (the index of the substring's first character); the parameter defaults to 0;end([group])method is used to get the ending position of a group-matched substring in the whole string (the index of the substring's last character + 1); the parameter defaults to 0;span([group])method returns(start(group), end(group)).
Let us look at another example:
Example
import
re
pattern
=
re
.
compile
(
r
'
([a-z]+) ([a-z]+)
'
,
re
.
I
)
re.I means ignoring case
m
=
pattern
.
match
(
'
Hello World Wide Web
'
)
m
Match succeeds, returning a Match object
<
_sre
.
SRE_Match
object
at
0
x10bea83e8
m
.
group
(
0
)
Return the whole successfully matched substring
'
Hello World
'
m
.
span
(
0
)
Return the index of the whole successfully matched substring
(
0
,
11
)
m
.
group
(
1
)
Return the substring successfully matched by the first group
'
Hello
'
m
.
span
(
1
)
Return the index of the substring successfully matched by the first group
(
0
,
5
)
m
.
group
(
2
)
Return the substring successfully matched by the second group
'
World
'
m
.
span
(
2
)
Return the substring successfully matched by the second group
(
6
,
11
)
m
.
groups
(
)
Equivalent to (m.group(1), m.group(2), ...)
(
'
Hello
'
,
'
World
'
)
m
.
group
(
3
)
There is no third group
Traceback
(
most
recent
call
last
)
:
File
"
"
,
line
1
,
in
<
module
IndexError
:
no
such
group
findall
Find all substrings in a string that match the regular expression and return a list; if there are multiple matching patterns, return a list of tuples; if no match is found, return an empty list.
Note: match and search match once, while findall matches all.
The syntax is:
findall(string[, pos[, endpos]])
Parameters:
- string : The string to be matched.
- pos : Optional parameter, specifying the starting position of the string, defaulting to 0.
- endpos : Optional parameter, specifying the ending position of the string, defaulting to the length of the string.
Find all numbers in a string:
Example
-- coding:UTF8 --
import
re
pattern
=
re
.
compile
(
r
'
\d
'
)
Find numbers
result1
=
pattern
.
findall
(
'
runoob 123 google 456
'
)
result2
=
pattern
.
findall
(
'
run88oob123google456
'
,
0
,
10
)
(
result1
)
(
result2
)
Output result:
['123', '456']
['88', '12']
Multiple matching patterns return a list of tuples:
Example
import
re
result
=
re
.
findall
(
r
'(\w+)=(\d+)'
,
'set width=20 and height=10'
)
(
result
)
[('width', '20'), ('height', '10')]
re.finditer
Similar to findall, it finds all substrings in a string that match the regular expression and returns them as an iterator.
re.finditer(pattern, string, flags=0)
Parameters:
| Parameters | Description |
|---|---|
| pattern | The regular expression to match |
| string | The string to be matched. |
| flags | Flags that control how the regular expression is matched, such as case sensitivity and multi-line matching. See:Regular expression modifiers - optional flags |
Example
-- coding: UTF-8 --
import
re
it
=
re
.
finditer
(
r
"
\d
"
,
"
12a32bc43jf3
"
)
for
match
in
it
:
(
match
.
group
(
)
)
Output result:
12
32
43
3
re.split
The split method splits a string by the substrings that can be matched and returns a list; it is used as follows:
re.split(pattern, string[, maxsplit=0, flags=0])
Parameters:
| Parameters | Description |
|---|---|
| pattern | The regular expression to match |
| string | The string to be matched. |
| maxsplit | The number of splits; maxsplit=1 splits once, and the default is 0, meaning no limit. |
| flags | Flags that control how the regular expression is matched, such as case sensitivity and multi-line matching. See:Regular expression modifiers - optional flags |
Example
import
re
re
.
split
(
'
\W
'
,
'
runoob, runoob, runoob.
'
)
[
'
runoob
'
,
'
runoob
'
,
'
runoob
'
,
'
'
]
re
.
split
(
'
(
\W
+)
'
,
'
runoob, runoob, runoob.
'
)
[
'
'
,
'
'
,
'
runoob
'
,
'
,
'
,
'
runoob
'
,
'
,
'
,
'
runoob
'
,
'
.
'
,
'
'
]
re
.
split
(
'
\W
'
,
'
runoob, runoob, runoob.
'
,
1
)
[
'
'
,
'
runoob, runoob, runoob.
'
]
re
.
split
(
'
a*
'
,
'
hello world
'
)
For a string where no match can be found, split does not split it
[
'
hello world
'
]
Regular expression objects
re.RegexObject
re.compile() returns a RegexObject object.
re.MatchObject
group() returns the string matched by the RE.
- start() returns the position where the match starts
- end() returns the position where the match ends
- span() returns a tuple containing the match (start, end) positions
Regular expression modifiers - optional flags
A regular expression can contain some optional flag modifiers to control the matching mode. A modifier is specified as an optional flag. Multiple flags can be specified by bitwise OR-ing (|) them. For example, re.I | re.M sets the I and M flags:
| Modifiers | Description |
|---|---|
| re.I | Make the match case-insensitive |
| re.L | Perform locale-aware matching |
| re.M | Multi-line matching, affecting ^ and $ |
| re.S | Make . match all characters including the newline |
| re.U | Parse characters according to the Unicode character set. This flag affects \w, \W, \b, \B. |
| re.X | This flag allows you to write regular expressions that are easier to understand by giving you a more flexible format. |
Regular expression patterns
Pattern strings use a special syntax to represent a regular expression:
Letters and digits represent themselves. Letters and digits in a regular expression pattern match the same strings.
Most letters and digits take on a different meaning when preceded by a backslash.
Punctuation marks match themselves only when escaped; otherwise they have special meanings.
A backslash itself needs to be escaped with a backslash.
Since regular expressions usually contain backslashes, it is best to use raw strings to represent them. Pattern elements (such as r'\t', equivalent to '\t') match the corresponding special characters.
The following table lists the special elements in regular expression pattern syntax. If you supply optional flag arguments along with the pattern, the meaning of some pattern elements changes.
| Mode | Description |
|---|---|
| ^ | Matches the beginning of a string |
| $ | Match the end of a string. |
| . | Match any character except a newline; when the re.DOTALL flag is specified, it can match any character including newlines. |
| [...] | Used to represent a set of characters, listed individually: [amk] matches 'a', 'm' or 'k' |
| [^...] | Characters not in []: [^abc] matches characters other than a, b and c. |
| re* | Match zero or more of the expression. |
| re+ | Match one or more of the expression. |
| re? | Match zero or one fragment defined by the preceding regular expression, in a non-greedy way |
| re{ n} | Matches exactly n occurrences of the preceding expression. For example, o{2} cannot match the "o" in "Bob", but can match the two o's in "food". |
| re{ n,} | Matches n occurrences of the preceding expression. For example, o{2,} cannot match the "o" in "Bob", but can match all the o's in "foooood". "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*". |
| re{ n, m} | Match n to m fragments defined by the preceding regular expression, in a greedy way |
| a| b | Match a or b |
| (re) | Group a regular expression and remember the matched text |
| (?imx) | The regular expression contains three optional flags: i, m or x. They affect only the region inside the parentheses. |
| (?-imx) | Turn off the i, m or x optional flags for the regular expression. They affect only the region inside the parentheses. |
| (?: re) | Similar to (...), but does not represent a group |
| (?imx: re) | Use the i, m or x optional flags inside parentheses |
| (?-imx: re) | Do not use the i, m or x optional flags inside parentheses |
| (?#...) | Comment. |
| (?= re) | Positive lookahead assertion. It succeeds if the contained regular expression, represented by ..., matches successfully at the current position, and fails otherwise. But once the contained expression has been tried, the matching engine has not advanced at all; the rest of the pattern must still be tried to the right of the assertion. |
| (?! re) | Negative lookahead assertion. The opposite of a positive lookahead; it succeeds when the contained expression cannot match at the current position in the string |
| (?> re) | An independent pattern for matching, eliminating backtracking. |
| \w | Match letters, digits and underscores |
| \W | Match anything that is not a letter, digit or underscore |
| \s | Match any whitespace character, equivalent to [ \t\n\r\f]. |
| \S | Match any non-whitespace character |
| \d | Match any digit, equivalent to [0-9]. |
| \D | Match any non-digit |
| \A | Match the start of a string |
| \Z | Match the end of a string; if a newline exists, it matches only the end of the string before the newline. |
| \z | Match the end of a string |
| \G | Match the position where the last match completed. |
| \b | Match a word boundary, that is, the position between a word and a space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in "verb". |
| \B | Match a non-word boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never". |
| \n, \t, etc. | Match a newline. Match a tab. etc. |
| \1...\9 | Match the content of the nth group. |
| \10 | Match the content of the nth group, if it has been matched. Otherwise it refers to an expression for an octal character code. |
Regular expression example
Character matching
| Example | Description |
|---|---|
| python | Match "python". |
Character class
| Example | Description |
|---|---|
| [Pp]ython | Match "Python" or "python" |
| rub[ye] | Match "ruby" or "rube" |
| [aeiou] | Match any one letter inside square brackets |
| [0-9] | Match any digit. Similar to [0123456789] |
| [a-z] | Match any lowercase letter |
| [A-Z] | Match any uppercase letter |
| [a-zA-Z0-9] | Match any letter and digit |
| [^aeiou] | All characters except the letters aeiou |
| [^0-9] | Match characters other than digits |
Special character classes
| Example | Description |
|---|---|
| . | Match any single character except "\n". To match any character including '\n', use a pattern like '[.\n]'. |
| \d | Match a digit character. Equivalent to [0-9]. |
| \D | Match a non-digit character. Equivalent to [^0-9]. |
| \s | Match any whitespace character, including spaces, tabs and form feeds. Equivalent to [ \f\n\r\t\v]. |
| \S | Match any non-whitespace character. Equivalent to [^ \f\n\r\t\v]. |
| \w | Match any word character including the underscore. Equivalent to '[A-Za-z0-9_]'. |
| \W | Match any non-word character. Equivalent to '[^A-Za-z0-9_]'. |