正则表达式(re模块)
正则表达式是一种强大的字符串匹配工具,可以用来查找、替换和解析字符串中的模式。Python中的 re
模块提供了对正则表达式的支持,包括 search()
、 match()
、 findall()
等方法。
1. re.match(pattern, string)
match(参数1,参数2)
从给定的字符串(参数2)的起始位置搜索匹配指定内容(参数1)。如果找到匹配,则返回匹配对象;如果没有找到匹配,则返回 None
。
import re
text = "Hello, world!"
match = re.match('Hello', text)
match1=re.match('ell',text)
print(match) #输出:<re.Match object; span=(0, 5), match='Hello'>
print(match1) #输出:None
2. re.search(pattern, string)
search(参数1,参数2)
尝试在给定的字符串(参数2)中匹配指定内容(参数1)。如果找到匹配,则返回匹配对象;如果匹配了多个对象,则返回第一个匹配对象的信息;如果没有找到匹配,则返回 None
。
import re
text = "Hello, world! wor"
match = re.search('Hello', text)
match1=re.search('wor',text)
match2=re.search('app',text)
print(match) #输出:<re.Match object; span=(0, 5), match='Hello'>
print(match1) #输出:<re.Match object; span=(7, 10), match='wor'>
print(match2) #输出:None
3. re.findall(pattern, string)
findall(参数1,参数2)
在给定的字符串(参数2)中查找匹配指定内容(参数1)的所有匹配项,并以列表的形式返回。
import re
text = "Hello, world! wor"
match1=re.findall('wor',text)
print(match1) #输出:['wor', 'wor']