我是 python 的新手。我想編寫一個正則表達式來使用 re.match 查找整個字符串。例如,word1=I word2=Ustr_to_match = word1+"[There could be some space in between]"+ word2[this is the end of string I want to match]"在這種情況下,它應該匹配I[0 or more spaces in between]U。它不應該匹配abI[0 or more spaces in between]U, OR abI[0 or more spaces in between]Ucd, OR I[0 or more spaces in between]Ucd。我知道你可以使用 boundary\b來設置單詞邊界,但由于 word1 和 word2 之間可能有許多空格,整個字符串就像一個變量,而不是一個固定的字符串,它對我不起作用:ret=re.match(r"\b"+word1+r"\s+" +word2+r"\b")不工作有誰知道我怎樣才能找到匹配這種情況的正確方法?謝謝!
1 回答

函數式編程
TA貢獻1807條經驗 獲得超9個贊
match 只匹配字符串的開頭。由于您使用的是 \b ,因此不應該是您想要的。 findall
將找到所有匹配的字符串。
如果你想找到第一個出現的地方并且只是測試它是否存在于字符串中,而不是找到你可以使用的所有匹配項search
:
word1 = 'I'
word2 = 'U'
ret = re.findall(rf"\b{word1}\s*{word2}\b"," I U IU I U aI U I Ub")
print(ret)
ret = re.search(rf"\b{word1}\s*{word2}\b"," IUb .I U ")
print(ret)
添加回答
舉報
0/150
提交
取消