搜索和匹配

使用正則運算式有兩個基本操作看起來相似但有顯著差異。 re.match()僅在字串的開頭檢查匹配,而re.search()檢查字串中任何位置的匹配。 這在文本處理中起著重要作用,因為通常必須編寫正確的正則運算式來檢索用於情感分析的文本塊作為示例。

import re

if  re.search("tor", "Tutorial"):
        print "1. search result found anywhere in the string"

if re.match("Tut", "Tutorial"):
         print "2. Match with beginning of string"

if not re.match("tor", "Tutorial"):
        print "3. No match with match if not beginning"



# Search as Match

if  not re.search("^tor", "Tutorial"):
        print "4. search as match"

當我們運行上面的程式時,得到以下輸出 -

1. search result found anywhere in the string
2. Match with beginning of string
3. No match with match if not beginning
4. search as match

上一篇: 閱讀RSS提要 下一篇: 文字改寫