Python正则表达式-有时模式可以在字符串的末尾,有时模式可以"在中间"



如果找到以下子文本,但子文本之前或之后不应有其他字母数字字符,则我需要返回匹配项。

例如:在文件名中搜索文本"OCI":

import re
file_pattern = r".*([^a-zA-Z0-9]OCI[^a-zA-Z0-9]).*"
text = "rce oci "
m = re.match(file_pattern, text, re.IGNORECASE) 
if m is not None:
print(m)
else:
print("no match found")

上述代码按预期工作text="rce-oci"->找到匹配项-注意此处的oci后面有一个额外的空白text="rceoci"->未找到匹配的

但如果text="rce-oci",它不会返回匹配项——请注意,这里没有多余的空白。

我怎么可能解决这个问题?

感谢

您可以在模式中使用单词边界,并将re.match更改为re.search:

import re
file_pattern = r"bOCIb"
text = "rce oci"
m = re.search(file_pattern, text, re.IGNORECASE) 
if m is not None:
print(m)
else:
print("no match found")

注意,re.match检查是否完全匹配,而更新后的模式并非如此。

最新更新