SoFunction
Updated on 2025-03-10

Examples of several methods for Python regular expressions

Preface

Calling method:

(pattern, string, flags=0)

Usage description:Scan the entire string to find all characters that satisfy the matching style, and collect them together and return them in a list form. The returned list contains empty results (no matching results).

Example 1

import re

str1 = "The telephone number of police in China is 110, and the telephone number of emergency is 120."
pattern = "\d+"
result = (pattern, str1)
print(result)
"""
result:
['110', '120']
"""

Can be seen. Through this matching method, we successfully find all the numeric objects in a string and collect them together as a list object and return them.

Example 2

import re

str1 = "I got 1.0, and my classmate got 2.0."
pattern = "\d+"
result = (pattern, str1)
print(result)
"""
result:
['1', '0', '2', '0']
"""

We want to get it through matching1.0and2.0These two numbers. However, things went against our expectations. We got four independent numbers. What should we do? The following code should be used:

import re

str1 = "I got 1.0, and my classmate got 2.0."
pattern = "\d.\d"
result = (pattern, str1)
print(result)
"""
result:
['1.0', '2.0']
"""

As you can see, we have successfully obtained the numbers we need.

Example Three

import re

str1 = "I got 1.0, and my classmate got 2.0."
pattern = "\d\d"
result = (pattern, str1)
print(result)
"""
result:
[]
"""

When we cannot find a matching object, an empty list object will be returned. This is with()The usage description of the function is consistent.

Summarize

This is the end of this article about several methods of Python regular expressions(). For more related contents of Python regular expressions(), please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!