Home > Article > Backend Development > How to use regular expressions in Python?
Python is a powerful programming language that supports the use of regular expressions for text manipulation. As data analysis and text processing become more and more common in all walks of life, mastering the skills of regular expressions has become an increasingly important basic skill. In this article, we will learn how to use regular expressions in Python.
Using regular expressions in Python requires importing the re module. Of course, before using regular expressions, we need to first be familiar with the syntax rules of regular expressions. Here are some basic regular expression symbols and their meanings:
Symbol | Meaning |
---|---|
. | Matches any character, except newline characters |
d | Matches digits |
D | matches non-digits |
w | matches letters, numbers, underscores or Chinese characters |
Matches other characters except letters, numbers, underscores or Chinese characters | |
Matches any white space characters, including spaces, tabs, and newlines Characters, etc. | |
matches any non-whitespace characters | |
matches the beginning of the string | |
Match the end of the string | |
Match 0 or more times | |
Match 1 or more times | |
Match 0 or 1 times | |
Match exactly n times | |
Match n times or more Multiple times | |
Match m~n times | |
Matches any characters in square brackets, including character ranges, excluded characters, etc. | |
Capture matching substrings | |
Does not capture matching substrings | |
Positive positive pre-check | |
Positive negative pre-check | |
Reverse positive pre-check | |
import re # 声明一个字符串 str1 = "hello world" # 定义正则表达式 pattern = "hello world" # 使用 re 模块进行匹配 result = re.search(pattern, str1) print(result.group())
hello world
# 定义正则表达式 pattern = r"w+($" # 使用 re 模块进行匹配 result = re.search(pattern, "I have a list (item1, item2).") print(result.group())
list(
# 定义正则表达式 pattern = r"https?://S+.w+(?<!/)$" # 使用 re 模块进行匹配 result = re.search(pattern, "Here is a link: https://www.google.com.") print(result.group())
https://www.google.com
# 定义正则表达式 pattern = r"w+@w+.w{2,3}" # 使用 re 模块进行匹配 result = re.findall(pattern, "Please contact me at alice@gmail.com or bob@hotmail.com") print(result)
['alice@gmail.com', 'bob@hotmail.com']
# 定义正则表达式 pattern = r"d" # 使用 re 模块进行匹配和替换 result = re.sub(pattern, "*", "12345678") print(result)
********
The above is the detailed content of How to use regular expressions in Python?. For more information, please follow other related articles on the PHP Chinese website!