re.match 从字符串的起始位置匹配,匹配不成功,match()就返回none。
re.match(pattern, string, flags=0)
函数参数说明:
- pattern 匹配的正则表达式
- string 要匹配的字符串。
- flags 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式修饰符,可选标志
import re
r1=re.match('hello', 'hello.word')
r2=re.match('1hello', 'hello.word')
print(r1)
print(r2)
执行结果
使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。
import re
s1='select * from world where "someone" like "%you%"'
r1=re.match(r'(.*) * from (.*?) .*',s1,re.M|re.I)
if r1:
print('r1.group():',r1.group())
print('r1.group(1):',r1.group(1))
print('r1.group(2):',r1.group(2))
else:
print('no')
运行结果:
re.search 扫描整个字符串并返回第一个成功的匹配。
import re
s1='select * from world where "someone" like "%you%"'
r1=re.search(r'from(.*?)like', s1)
print(r1)
#返回match object
print(r1.group(1))
如果没有匹配上 返回none 但group(1)会报错 此时需要加个判断
import re
s1='select * from world where "someone" like "%you%"'
r1=re.search(r'11from(.*?)like', s1)
print(r1)
result=r1.group(1) if r1 else None
print(result)
# 返回2个NONe