import re
"""
1、re.match,re.match尝试从字符串的起始位置匹配一个模块,如果不是起始位置匹配成功的话
match()就返回none
re.match(pattern, string ,flags = 0)
"""
最常规匹配
content = "Hello 123 4567 World_This is a Regex Demo"
print(len(content))
result1 = re.match('^Hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$',content)
print(result1)
print(result1.group())#group()输出匹配到的结果
print(result1.span())#span()返回范围
泛匹配
result2 = re.match('^Hello.Demo$', content)#.可以匹配到中间所有的除换行符外的字符
print(result2)
print(result2.group())#group()输出匹配到的结果
print(result2.span())#span()返回范围
匹配目标
content1 = "Hello 1234567 World_This is a Regex Demo"
result3 = re.match('^Hello\s(\d+)\sWorld.*Demo$',content1)#把要匹配的用小括号括起来,指定左右端点
print(result3)
print(result3.group(1))#group()输出匹配到的结果,1表示第一个括号
print(result3.span())#span()返回范围
贪婪匹配
content1 = "Hello 1234567 World_This is a Regex Demo"
result4 = re.match('^He.(\d+).Demo$',content1)#.会尽可能多的匹配,直到最后匹配不到为止,所以这里的123456都被.所代替
print(result4)
print(result4.group(1))
非贪婪匹配
content1 = "Hello 1234567 World_This is a Regex Demo"
result5 = re.match('^He.?(\d+).Demo$',content1)#?可以指定为一个非贪婪匹配,会匹配尽可能少的字符
print(result5)
print(result5.group(1))
匹配模式
content2 = '''Hello 1234567 World_This
is a Regex Demo'''
result6 = re.match('^He.?(\d+).?Demo$',content2,re.S)#不加re.S的话会因为换行的原因而无法匹配
print(result6.group(1))
转义,特殊字符需要进行转义
content3 = 'price is $5.00'
result7 = re.match('price is $5.00',content3)
print(result7)
re.search,扫描整个字符串并返回第一个成功的匹配
content4 = "Extra string Hello 1234567 World_This is a Regex Demo Extra string"
result8 = re.search('Hello.?(\d+).?Demo',content4)
print(result8)
print(result8.group(1))