在python里有强大的正则表达式模块re,用来它进行模式匹配是非常方便的,比如下面的例子,就是用来从一段文字里查找一个单词,如下:
import re
pattern = 'this'
text = 'http://blog.youkuaiyun.com/caimouse is great, this is great way!'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "{}"\nin "{}"\nfrom {} to {} ("{}")'.format(
match.re.pattern, match.string, s, e, text[s:e]))
结果输出如下:
Found "this"
in "http://blog.youkuaiyun.com/caimouse is great, this is great way!"
from 40 to 44 ("this")
在这里使用start()表示匹配的开始位置,end()表示结束位置。