正則表示式 match() 和 regex search() 函式在 Python 中的重要性


使用 正則表示式有兩種型別的操作,(a) 搜尋和 (b) 匹配。為了在查詢模式和與該模式匹配時有效地使用正則表示式,可以使用這兩個函式。

讓我們考慮我們有一個字串。正則表示式 match() 僅檢查字串開頭的模式,而 正則表示式 search() 檢查字串中任何位置的模式。如果找到模式,match() 函式則返回 匹配 物件,否則返回無。

  • match() – 僅查詢字串開頭的模式,並返回匹配的物件。
  • search() – 在字串中任何位置檢查模式,並返回匹配的物件。

在此示例中,我們有一個字串,需要在此字串中查詢單詞“engineer”。

示例

即時演示

import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.match(pattern, string)
if result:
   print("Found")
else:
   print("Not Found")

執行此程式碼將列印輸出為:

輸出

Not Found

現在,讓我們對上述示例進行搜尋,

示例

即時演示

import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.search(pattern, string)
if result:
   print("Found")
else:
   print("Not Found")

執行上述程式碼將列印輸出為:

輸出

Found

更新日期:23-Feb-2021

540 人檢視

開啟您的 職業

完成課程認證

開始
廣告