import re
x = 'The car parked in the garage.'
print(re.findall(r'[^c]ar',x))
结果返回列表
['par', 'gar']
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
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
从头开始匹配
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)