我想匹配“python”:
re.match("python", "python programming") # --> True
我想排除“python”后面除了空格之外的其他内容的可能性,所以我想:
re.match("python[^ ]", "python3 programming") # --> False
问题是,如果它只是“python”,我仍然想匹配:
re.match("python[^ ]", "python") # --> False (Should be True)
将其设为可选不起作用,因为这样它将与前面的情况匹配,而应该返回 false:
re.match("python[^ ]?", "python3 programming") # --> True (Should be False)
re.match("python[^ ]?", "python") # --> True
“programming python”的情况类似,也应该匹配“python”。
我在这里缺少什么概念,以便所有匹配都是正确的?
最佳答案
您可以检查单词边界\b
:
>>> re.search(r"\bpython\b", "python programming")
<_sre.SRE_Match object at 0xb72be5d0>
>>> print re.search(r"\bpython\b", "python3")
None
>>> re.search(r"\bpython\b", "programming python")
<_sre.SRE_Match object at 0xb72be5d0>
关于python - 缺少匹配的正则表达式概念(搜索前瞻),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18802495/