re模块的使用

re.findall(parttern,string,flag)

import re
x = 'The car parked in the garage.'
print(re.findall(r'[^c]ar',x))

结果返回列表

['par', 'gar']

re.finditer(pattern, string, flags=0) 这种方式效率更高

import re
x = 'The car parked in the garage.'
result=re.finditer(r'[^c]ar',x)
print(result)
for r2 in result:
    print(r2.group())

result是结果的迭代器,结果

<callable_iterator object at 0x0000015496F06950>
par
gar

re.search(pattern, string, flags=0)

search找到一个匹配的就返回

import re
x = 'The car parked in the garage.'

result=re.search(r'[^c]ar',x)
print(result)
print(result.group())

结果:

<re.Match object; span=(8, 11), match='par'>
par

re.match()

从头开始匹配

import re
x = 'The car parked in the garage.'

result=re.match(r'[^c]ar',x)
print(result)

预加载正则表达式

用于正则表达式特别长的时候

import re
#预加载正则表达式
regex=re.compile(r'[^c]ar')

x = 'The car parked in the garage.'
result1=re.finditer(regex,x)

result2=regex.findall(x)

print(result1)
for r in result1:
    print(r.group())

print(result2)

你可能感兴趣的:(python)