如何匹配一个不以X开头但以Y结尾的单词与正则表达式匹配

时间:2010-06-21 18:33:57

标签: python regex

实施例

X=This
Y=That

不匹配;

ThisWordShouldNotMatchThat
ThisWordShouldNotMatch
WordShouldNotMatch

匹配

AWordShouldMatchThat

我试过(?<!...),但似乎并不容易:)

1 个答案:

答案 0 :(得分:12)

^(?!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是单词边界锚,因此它在单词的开头和结尾处匹配。 \w表示“字母数字字符。如果您还想允许非字母数字作为”单词“的一部分,请使用\S代替 - 这将匹配任何不是空格的内容。

在Python中,您可以words = re.findall(r"\b(?!This)\w*That\b", text)