例子;
X=This
Y=That
不匹配;
ThisWordShouldNotMatchThat
ThisWordShouldNotMatch
WordShouldNotMatch
匹配;
AWordShouldMatchThat
我试过了 (?<!...)但似乎并不容易:)
请您参考如下方法:
^(?!This).*That$
作为自由间距的正则表达式:
^ # 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
这将匹配满足您的条件的单个单词,但前提是该单词是正则表达式的唯一输入。如果您需要在包含许多其他单词的字符串中查找单词,请使用
\b(?!This)\w*That\b
\b 是单词边界 anchor ,所以它匹配单词的开头和结尾。 \w 表示“字母数字字符。如果您还想允许非字母数字字符作为您的“单词”的一部分,那么请改用 \S - 这将匹配任何不是一个空间。
在 Python 中,您可以执行 words = re.findall(r"\b(?!This)\w*That\b", text)。
