搜索和匹配

使用正則表達式有兩個基本操作看起來相似但有顯着差異。 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