Alex Rivera | Logout

Regular expressions: find string without substring

Asked 2012-08-08T17:18:16.453
30

I have a big text:

"Big piece of text. This sentence includes 'regexp' word. And this
sentence doesn't include that word"

I need to find substring that starts by 'this' and ends by 'word' but doesn't include word 'regexp'.

In this case the string: "this sentence doesn't include that word" is exactly what I want to receive.

How can I do this via Regular Expressions?

Edit
Report

1 Answer

49

With an ignore case option, the following should work:

\bthis\b(?:(?!\bregexp\b).)*?\bword\b

Example: http://www.rubular.com/r/g6tYcOy8IT

Explanation:

\bthis\b           # match the word 'this', \b is for word boundaries
(?:                # start group, repeated zero or more times, as few as possible
   (?!\bregexp\b)    # fail if 'regexp' can be matched (negative lookahead)
   .                 # match any single character
)*?                # end group
\bword\b           # match 'word'

The \b surrounding each word makes sure that you aren't matching on substrings, like matching the 'this' in 'thistle', or the 'word' in 'wordy'.

This works by checking at each character between your start word and your end word to make sure that the excluded word doesn't occur.

answered 2012-08-08T17:25:39.510

Your Answer