re.match():包含有关搜索和结果信息的对象。如果没有匹配,则返回值 None,而不是 Match 对象。从第一个开始匹配。
示例代码1:
import re
s = "Long live the people's Republic of China"
ret1 = re.match('Long', s)
print(ret1)
ret2 = re.match('the', s)
print(ret2)
运行结果:
示例代码2:
import re
# password = 'abca'
password = 'ab123ca'
if re.match(r'.*[0-9].*', password):
print('密码格式正确!')
else:
print('密码格式不正确!')
运行结果:
示例代码3:
import re
s = "Long live the people's Republic of China"
ret1 = re.search('Long', s)
print(ret1)
ret2 = re.search('the', s)
print(ret2)
运行结果:
Match 对象提供了用于取回有关搜索及结果信息的属性和方法:
- span() 返回的元组包含了匹配的开始和结束位置
- .string 返回传入函数的字符串
- group() 返回匹配的字符串部分
示例代码4:
import re
s = "Long live the people's Republic of China"
ret1 = re.search('Long', s)
print(ret1)
print(ret1.span())
print(ret1.string)
print(ret1.group())
print("*" * 50)
ret2 = re.search('the', s)
print(ret2)
print(ret2.span())
print(ret2.string)
print(ret2.group())
运行结果: