前言
在python中,通過內嵌集成re模塊,程序媛們可以直接調用來實現正則匹配。正則表達式模式被編譯成一系列的字節碼,然后由用C編寫的匹配引擎執行。
比如下面的例子,就是用來從一段文字里查找一個單詞,如下:
示例代碼
1
2
3
4
5
6
7
8
9
10
11
12
|
import re pattern = 'this' text = 'http://blog.csdn.net/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])) |
結果輸出如下:
1
2
3
|
Found "this" in "http://blog.csdn.net/caimouse is great, this is great way!" from 40 to 44 ("this") |
在這里使用start()
表示匹配的開始位置,end()表示結束位置。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:http://blog.csdn.net/caimouse/article/details/78069953