RegEx 或正则表达式是形成搜索模式的字符序列。
RegEx 可用于检查字符串是否包含指定的搜索模式。
RegEx 模块
Python 提供名为 re 的内置包,可用于处理正则表达式。
导入 re 模块:
import re
Python 中的 RegEx
导入 re 模块后,就可以开始使用正则表达式了:
实例
检索字符串以查看它是否以 “China” 开头并以 “country” 结尾:
import re
txt = "China is a great country"
x = re.search("^China.*country$", txt)
运行实例
import re
txt = "China is a great country"
x = re.search("^China.*country$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")
RegEx 函数
re 模块提供了一组函数,允许我们检索字符串以进行匹配:
元字符
元字符是具有特殊含义的字符
字符:[]
描述:一组字符
示例:“[a-m]”
import re
str = "The rain in Spain"
#Find all lower case characters alphabetically between "a" and "m":
x = re.findall("[a-m]", str)
print(x)
运行示例
字符:
描述:示意特殊序列(也可用于转义特殊字符)
示例:“\d”
import re
str = "That will be 59 dollars"
#Find all digit characters:
x = re.findall("\d", str)
print(x)
运行示例
字符:.
描述:任何字符(换行符除外)
示例: “he…o”
import re
str = "hello world"
#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":
x = re.findall("he..o", str)
print(x)
运行示例
字符:^
描述:起始于
示例: “^hello”
import re
str = "hello world"
#Check if the string starts with 'hello':
x = re.findall("^hello", str)
if (x):
print("Yes, the string starts with 'hello'")
else:
print("No match")
运行示例
字符:$
描述:结束于
示例:“world$”
import re
str = "hello world"
#Check if the string ends with 'world':
x = re.findall("world$", str)
if (x):
print("Yes, the string ends with 'world'")
else:
print("No match")
运行示例
字符:*
描述:零次或多次出现
示例:“aix*”
import re
str = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" followed by 0 or more "x" characters:
x = re.findall("aix*", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
运行示例
字符:+
描述:一次或多次出现
示例: “aix+”
import re
str = "The rain in Spain falls mainly in the plain!"
#Check if the string contains "ai" followed by 1 or more "x" characters:
x = re.findall("aix+", str)
print(x)
if (x):
print("Yes, there is at least one match!")
else:
print("No match")
运行示例
字符:{}
描述: 确切地指定的出现次数
示例:“al{2}”
import re
str = "The rain in Spain falls mainly in the plain!&