Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Regular Expressions

Python3 Regular Expressions

A regular expression is a special sequence of characters that helps you conveniently check whether a string matches a certain pattern.

In Python, the re module is used to handle regular expressions.

The re module provides a set of functions that let you perform pattern matching, searching and replacement in strings.

The re module gives the Python language full regular expression functionality.

This chapter mainly introduces the commonly used regular expression functions in Python; if you are not familiar with regular expressions, see our Regular Expressions - Tutorial。


The re.match function

re.match tries to match a pattern from the beginning of a string; if the match does not succeed at the starting 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

On a successful match 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

import

re

print

(

re

.

match

(

'

www

'

,

'

www.runoob.com

'

)

.

span

(

)

)

Match at the starting position

print

(

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/python3

import

re

line

=

"

Cats are smarter than dogs

"

.* means matching any single or multiple characters except newline characters (\n, \r)

(.*?) means the "non-greedy" mode, saving only the first matched substring

matchObj

=

re

.

match

(

r

'

(.) are (.?) .*

'

,

line

,

re

.

M

|

re

.

I

)

if

matchObj

:

print

(

"

matchObj.group() :

"

,

matchObj

.

group

(

)

)

print

(

"

matchObj.group(1) :

"

,

matchObj

.

group

(

1

)

)

print

(

"

matchObj.group(2) :

"

,

matchObj

.

group

(

2

)

)

else

:

print

(

"

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 that control how the regular expression is matched, such as case sensitivity and multi-line matching. See:Regular expression modifiers - optional flags

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/python3

import

re

print

(

re

.

search

(

'

www

'

,

'

www.runoob.com

'

)

.

span

(

)

)

Match at the starting position

print

(

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/python3

import

re

line

=

"

Cats are smarter than dogs

"

searchObj

=

re

.

search

(

r

'

(.) are (.?) .*

'

,

line

,

re

.

M

|

re

.

I

)

if

searchObj

:

print

(

"

searchObj.group() :

"

,

searchObj

.

group

(

)

)

print

(

"

searchObj.group(1) :

"

,

searchObj

.

group

(

1

)

)

print

(

"

searchObj.group(2) :

"

,

searchObj

.

group

(

2

)

)

else

:

print

(

"

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 a string; if the beginning does not match the regular expression, the match fails and the function returns None, whereas re.search matches the whole string until it finds a match.

Example

#!/usr/bin/python3

import

re

line

=

"

Cats are smarter than dogs

"

matchObj

=

re

.

match

(

r

'

dogs

'

,

line

,

re

.

M

|

re

.

I

)

if

matchObj

:

print

(

"

match --> matchObj.group() :

"

,

matchObj

.

group

(

)

)

else

:

print

(

"

No match!!

"

)

matchObj

=

re

.

search

(

r

'

dogs

'

,

line

,

re

.

M

|

re

.

I

)

if

matchObj

:

print

(

"

search --> matchObj.group() :

"

,

matchObj

.

group

(

)

)

else

:

print

(

"

No match!!

"

)

The above example produces the following result:


No match!!
search --> matchObj.group() :  dogs

Search and replace

Python's re module provides re.sub to replace matches in a string.

Syntax:


re.sub(pattern, repl, string, count=0, flags=0)

Parameters:

The first three are required parameters and the last two are optional.

Example

#!/usr/bin/python3

import

re

phone

=

"

2004-959-559 # This is a phone number

"

Delete the comment

num

=

re

.

sub

(

r

'

#.*$

'

,

"

"

,

phone

)

print

(

"

Phone number :

"

,

num

)

Remove non-numeric content

num

=

re

.

sub

(

r

'

\D

'

,

"

"

,

phone

)

print

(

"

Phone number :

"

,

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

import

re

Multiply the matched number by 2

def

double

(

matched

)

:

value

=

int

(

matched

.

group

(

'

value

'

)

)

return

str

(

value

2

)

s

=

'

A23G4HFD567

'

print

(

re

.

sub

(

'

(?P

\d

+)

'

,

double

,

s

)

)

The execution output is:

A46G8HFD1134

The compile function

The compile function compiles a regular expression, producing a regular expression (Pattern) object for use by the match() and search() functions.

The syntax is:

re.compile(pattern[, flags])

Parameters:

These flags can be used individually or combined with bitwise OR (|). For example, re.IGNORECASE | re.MULTILINE enables both case-insensitive and multi-line modes.

- re.L makes the special character sets \w, \W, \b, \B, \s, \S depend on the current environment - re.MULTILINE or re.M - multi-line mode, changing the behavior of ^ and $ so they match the beginning and end of each line of the string. - re.DOTALL or re.S - makes . match any character including newline characters. - re.ASCII - makes \w, \W, \b, \B, \d, \D, \s, \S match ASCII characters only. - re.VERBOSE or re.X - ignore whitespace and comments, allowing complex regular expressions to be organized more clearly.

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

print

(

m

)

None

m

=

pattern

.

match

(

'

one12twothree34four

'

,

2

,

10

)

Start matching from the position of 'e', no match

print

(

m

)

None

m

=

pattern

.

match

(

'

one12twothree34four

'

,

3

,

10

)

Start matching from the position of '1', an exact match

print

(

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:

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

'

)

print

(

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 index of 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:


re.findall(pattern, string, flags=0)
或
pattern.findall(string[, pos[, endpos]])

Parameters:

  • pattern is the matching pattern.
  • string is the string to be matched.
  • pos is an optional parameter specifying the starting position of the string, defaulting to 0.
  • endpos is an optional parameter specifying the ending position of the string, defaulting to the length of the string.

Find all numbers in a string:

Example

import

re

result1

=

re

.

findall

(

r

'

\d

'

,

'

runoob 123 google 456

'

)

pattern

=

re

.

compile

(

r

'

\d

'

)

Find numbers

result2

=

pattern

.

findall

(

'

runoob 123 google 456

'

)

result3

=

pattern

.

findall

(

'

run88oob123google456

'

,

0

,

10

)

print

(

result1

)

print

(

result2

)

print

(

result3

)

Output result:


['123', '456']
['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'

)

print

(

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

import

re

it

=

re

.

finditer

(

r

"

\d

"

,

"

12a32bc43jf3

"

)

for

match

in

it

:

print

(

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 0 means 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 optional flag modifiers to control the matching mode.

The following flags can be used individually or combined with bitwise OR (|). For example, re.IGNORECASE | re.MULTILINE enables both case-insensitive and multi-line modes.

Modifiers Description Example
re.IGNORECASE or re.I Make the match case-insensitive

    

import re pattern = re.compile(r'apple', flags=re.IGNORECASE) result = pattern.match('Apple') print(result.group()) # Output: 'Apple' | | re.MULTILINE or re.M | Multi-line matching, affects ^ and $ so they match the beginning and end of each line of the string. |

import re
pattern = re.compile(r'^\d+', flags=re.MULTILINE)
text = '123\n456\n789'
result = pattern.findall(text)
print(result)  # 输出: ['123', '456', '789']
| | re.DOTALL or re.S: | Makes . match any character including newline characters. |
import re
pattern = re.compile(r'a.b', flags=re.DOTALL)
result = pattern.match('a\nb')
print(result.group())  # 输出: 'a\nb'
| | re.ASCII | Makes \w, \W, \b, \B, \d, \D, \s, \S match ASCII characters only. |
import re
pattern = re.compile(r'\w+', flags=re.ASCII)
result = pattern.match('Hello123')
print(result.group())  # 输出: 'Hello123'
| | re.VERBOSE or re.X | Ignores whitespace and comments, allowing complex regular expressions to be organized more clearly. |
import re
pattern = re.compile(r'''
\d+  # 匹配数字
[a-z]+  # 匹配小写字母
''', flags=re.VERBOSE)
result = pattern.match('123abc')
print(result.group())  # 输出: '123abc'
|


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, you had better use raw strings to represent them. A pattern element (such as r'\t', equivalent to \t ) matches the corresponding special character.

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 match any one of the contained characters, e.g. [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} Match n 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,} Match exactly n 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+", and "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) Match the expression inside parentheses, also indicating a group
(?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 assertion; 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 digits, letters and underscores
\W Match characters other than digits, letters and underscores
\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 character. Match a tab character, 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_]'.