开发者

How to match a word that doesn't start with X but ends with Y with regex

开发者 https://www.devze.com 2023-01-04 10:19 出处:网络
Example; X=This Y=That not matching; ThisWordSh开发者_运维问答ouldNotMatchThat ThisWordShouldNotMatch

Example;

X=This
Y=That

not matching;

ThisWordSh开发者_运维问答ouldNotMatchThat
ThisWordShouldNotMatch
WordShouldNotMatch

matching;

AWordShouldMatchThat

I tried (?<!...) but seems not to be easy :)


^(?!This).*That$

As a free-spacing regex:

^             # 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

This will match a single word that fulfills your criteria, but only if this word is the only input to the regex. If you need to find words inside a string of many other words, then use

\b(?!This)\w*That\b

\b is the word boundary anchor, so it matches at the start and at the end of a word. \w means "alphanumeric character. If you also want to allow non-alphanumerics as part of your "word", then use \S instead - this will match anything that's not a space.

In Python, you could do words = re.findall(r"\b(?!This)\w*That\b", text).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号