1.查找文本中的模式:search()
import re
text = "you are python"
match = re.search('are',text)
# 返回'are'第一个字符在text中的位置,注意是从0开始
print(match.start())
# 返回'are'最后一个字符在text中的位置,这里是从1开始
print(match.end())
结果:
4
7
2.编译表达式:compile()
import re
text = "you are SB"
# compile()函数会把一个表达式字符串转化为一个RegexObject
regexes = {re.compile(p)
for p in ['SB','NB','MB']
}
for regex in regexes:
if regex.search(text):
print('seeking ' + regex.pattern + ' >> match')
else:
print('seeking ' + regex.pattern + ' >> not match')
结果:
seeking NB >> not match
seeking SB >> match
seeking MB >> not match
3.多重匹配:findall(), finditer()
findall()函数会返回与模式匹配而不重叠的所有字符串。
import re
text = "ab aa ab bb ab ba"
# 把text所有的'ab'组合都匹配出来
print(re.findall('ab',text))
结果:
['ab', 'ab', 'ab']
finditer()会返回一个迭代器
import re
text = "ab aa ab bb ab ba"
for match in re.finditer('ab',text):
s = match.start()
e = match.end()
print('found {} at {} to {}'.format('"ab"',str(s),str(e)))
结果:
found "ab" at 0 to 2
found "ab" at 6 to 8
found "ab" at 12 to 14