0

Seemed like a trivial task to me but a failed to accomplish this in the past one hour.

The regular expression should match every word that does not contain the phrase 'exclude phrase'.

For instance:
Match:
'ok string'
'some phrasOk because thre is no e in phrase'
etc...

Not match:
'exclude phrase'
'Some prefix exclude phrase'
'exclude phrase some suffix'
etc...

Cœur
  • 37,241
  • 25
  • 195
  • 267
Nas
  • 1,063
  • 2
  • 9
  • 22
  • 1
    probable duplicate of http://stackoverflow.com/questions/611883/regex-how-to-match-everything-except-a-particular-pattern and http://stackoverflow.com/questions/1687620/regex-match-everything-but – olly_uk Jun 26 '12 at 11:33
  • 2
    possible duplicate of http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word – Gryphius Jun 26 '12 at 11:34

3 Answers3

2

If you have a phrase:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

The regex to find all words, but not 'sit' and 'adipiscing' will be:

\b(?(?=sit|adipiscing)^\w+|\w+)\b

In php:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';

$matches = array();
preg_match_all("/\b(?(?=sit|adipiscing)^\w+|\w+)\b/i", $text,$matches);

var_dump($matches);
Peter Adrian
  • 279
  • 1
  • 5
1

That would be a regex ^((?!phrase).)*$

Ωmega
  • 42,614
  • 34
  • 134
  • 203
1

Easiest way to solve this : regex for matching (trivial) then reverse condition.

Example in python:

>>> not(re.search ('exclude phrase','Some prefix exclude phrase'))
False
>>> not(re.search ('exclude phrase','exclude phrase some suffix'))
False
>>> not(re.search ('exclude phrase','ok string'))
True
Bruce
  • 7,094
  • 1
  • 25
  • 42
  • Thanks for he answer, Bruce. I figure it out that with a programing language it is easy to accomplish. But this is not working for me. I need a pure Regex to acomplish the reverse check. – Nas Jun 26 '12 at 12:10