Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preg_match exclude word from text

I have string:

FirstWord word2 word3 wrongWord word4 lastWord

Want to select string starts with FirstWord, ends with lastWord and doesn't contain wrongWord.

For first and last I have:

/firstword (.*?) lastword/i

but excluding wrongword didn't work.

Tried:

/firstword (^wrongWord*?) lastword/i

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

and more like this, but nothing works.

like image 210
Narek Avatar asked Dec 08 '22 11:12

Narek


1 Answers

What's wrong with simply the following?

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

See 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
like image 187
hwnd Avatar answered Dec 11 '22 01:12

hwnd