tags:

views:

114

answers:

1

Example;

X=This
Y=That

not matching;

ThisWordShouldNotMatchThat
ThisWordShouldNotMatch
WordShouldNotMatch

matching;

AWordShouldMatchThat

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

+10  A: 
^(?!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).

Tim Pietzcker
+1 - Simple and Accurate
gnarf
I appreciate your honest critique with no smart ass comments. I of course am bowing out now.
ChaosPandion
@ChaosPandion, I suggest you undelete your answer and modify the regex to use lookahead and lookbehind - I find it rather elegant and would upvote it immediately. It might even be faster than mine because the regex engine doesn't have to do any backtracking. The only disadvantage I can think of is that it wouldn't work in JavaScript or Ruby 1.8 because those don't support lookbehind.
Tim Pietzcker
Thanks for the answer but I think one point missed here is -word- not a sequence of letters here is the test http://regexr.com?2rka3
erdogany
The regex works fine when applied to individual words. In your test, the words are sprinkled across lines with more other words in between. You could have put this in the specification.
Tim Pietzcker
@Tim Pietzcker that's right so it is good point for me to learn if words are individual or among others makes a big difference, thanks again...
erdogany