例;
X=This
Y=That
Run Code Online (Sandbox Code Playgroud)
不匹配;
ThisWordShouldNotMatchThat
ThisWordShouldNotMatch
WordShouldNotMatch
Run Code Online (Sandbox Code Playgroud)
匹配;
AWordShouldMatchThat
Run Code Online (Sandbox Code Playgroud)
我试过(?<!...)但似乎并不容易:)
Tim*_*ker 13
^(?!This).*That$
Run Code Online (Sandbox Code Playgroud)
作为自由间距正则表达式:
^ # Start of string
(?!This) # Assert that "This" can't be matched here
.* # Match the rest of the string
That # making sure we match "That"
$ # right at the end of the string
Run Code Online (Sandbox Code Playgroud)
这将匹配符合您标准的单个单词,但前提是此单词是正则表达式的唯一输入.如果你需要在许多其他单词的字符串中找到单词,那么使用
\b(?!This)\w*That\b
Run Code Online (Sandbox Code Playgroud)
\b是单词边界锚,因此它匹配单词的开头和结尾.\w意思是"字母数字字符.如果你也想让非字母数字作为你的"字"的一部分,那么请\S改用 - 这将匹配任何不是空格的东西.
在Python中,你可以做到words = re.findall(r"\b(?!This)\w*That\b", text).