Preg_match excludes a word from text

I have a line:

FirstWord word2 word3 incorrect word Word4 lastWord

Want to choose a line that starts with FirstWord, ends with lastWordand does not contain wrongWord.

For the first and last I have:

/ firstword (. *?) lastword / i

but the exception wrongWorddoes not work.

I tried:

/ firstword (^ wrongWord *?) lastword / i

/ firstword ^ ((! wrongWord).) * lastword / i

and the like, but nothing works.

+4
source share
4 answers

What's wrong with that?

/^firstword ((?:(?!wrongword).)+) lastword$/i

Cm. live demo

Regular expression:

^              the beginning of the string
 firstword     'firstword '
 (             group and capture to \1:
  (?:          group, but do not capture (1 or more times)
   (?!         look ahead to see if there is not:
    wrongword  'wrongword'
   )           end of look-ahead
   .           any character except \n
  )+           end of grouping
 )             end of \1
 lastword      ' lastword'
$              before an optional \n, and the end of the string
+6
source

You can use this trick:

/^firstword ((?:[^w]+?|\Bw|w(?!rongword\b))*?) lastword$/i

or more efficiently:

/^firstword ((?>[^w\s]++|\s(?!lastword$)|\Bw|w(?!rongword\b))*+) lastword$/i
+2
source

. .

/firstword((?!wrongword).)*lastword/i
+2

What if the forbidden word is part of a longer word? For example, what if you want the lines to start with "first" and end with "last", but not contain the word "word"? For example:

"first one two word last"              # don't match
"first three wordplay four last"       # OK
"first five swordfish six seven last"  # OK

Adapting the accepted answer will give you the following:

/^first (?:(?!word).)+ last$/i

... but this will reject all three lines. In any case, there is no need to view in each position. Just do it once at the beginning of each word:

/^first(?:\s+(?!word\b)\w+)*\s+last$/i

Watch a live demo

+1
source

All Articles