我想匹配“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
:您可以显式添加特殊情况:
(python[^ ])|(python$)
使用negative lookahead assertion:
(?!\S)
表示“确保不可能在regex引擎的当前位置之后匹配除空格以外的字符”。如果当前位置后面有空白字符或没有任何内容,则为真。你知道吗相关问题 更多 >
编程相关推荐