[英]How to find specific regex in Python
我想制作一個數據分析腳本,因此我正在檢查 excel 工作表的單元格是否出現錯誤代碼。 對於每個錯誤代碼,我遍歷我的錯誤代碼列表並檢查每個代碼是否在該單元格中有正則表達式匹配。
有些代碼有 4 位,有些有 6 位。
現在的問題是,對於本身某處與 4 位代碼之一具有相同序列的所有 6 位代碼,該 4 位代碼有一個正則表達式匹配,即使該 4 位代碼不匹配也會被計算在內。 t 發生在這個單元格中。
這是一個小代碼示例,我認為它使問題變得很清楚。
errorcodes = [1234, 123456]
cell = "This is the cell containing the error 123456"
counter = 0
for i in range(2):
if re.search(str(errorcodes[i]), cell):
counter += 1
if counter == 2:
print("This is the wrong number of errors")
elif counter == 1:
print("This is the right number of errors")
要求正則表達式搜索方法在字符串123456
中查找1234
,因此它確實找到了匹配項。 但當然,當您查找123456
時,它也會找到匹配項。 您想要的是只找到整個錯誤代碼的匹配項。
您可以通過搜索單詞邊界之間的字符串來做到這一點。 單詞邊界由正則表達式元字符\b
表示,您可以像這樣使用它:
re.search(rf"\b{errorcodes[i]}\b", cell)
作為代碼修訂版的一部分:
import re
errorcodes = [1234, 123456]
cell = "This is the cell containing the error 123456"
counter = 0
for i in range(2):
if re.search(rf"\b{errorcodes[i]}\b", cell):
counter += 1
if counter == 2:
print("This is the wrong number of errors")
elif counter == 1:
print("This is the right number of errors")
我決定使用 Python 3.6 的 f 格式字符串,以便更輕松地指定搜索正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.