re.search(pattern,string,flags=0)
用于整个字符串中搜索第一个匹配的值,如果匹配成功,结果为Match对象,否则结果位None。
import re
pattern='\d\.\d+'
s='I study Python3.11 every day Python2.7 I love you'
match=re.search(pattern,s)
print(match) #<re.Match object; span=(14, 18), match='3.11'>
s2='4.10 Python I study every day'
s3='I study Python every day'
match2=re.search(pattern,s2) #<re.Match object; span=(0, 4), match='4.10'>
match3=re.search(pattern,s3) #None
print(match2)
print(match3)
print(match.group())
print(match2.group())
re.findall(pattern,string,flags=0)
用于在整个字符串搜索所有符合正则表达式的值,结果是一个列表类型。
import re
pattern='\d\.\d+'
s='I study Python3.11 every day Python2.7 I love you'
s2='4.10 Python I study every day'
s3='I study Python every day'
lst=re.findall(pattern,s)
lst2=re.findall(pattern,s2)
lst3=re.findall(pattern,s3)
print(lst)
print(lst2)
print(lst3)