Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture with negative look behind

Tags:

regex

php

pcre

Let's assume I have the following subject:

abcdef ghidef

and I want to match word ending with def not preceeded by abc (in this case it would be ghidef). How can I match this?

When I use:

(?<!abc)def

I'm getting the 2nd def but I'm not getting ghi here.

like image 360
Marcin Nabiałek Avatar asked Oct 18 '22 15:10

Marcin Nabiałek


1 Answers

No need of lookbehind. You can use with a negative lookahead:

\b(?!abc)\w*def\b

RegEx Demo

RegEx Breakup:

  • \b - assert a word boundary
  • (?!abc) - is negative lookahead that asserts a word doesn't start with abc after \b (word boundary)
  • \w* - match 0 or more word characters
  • def - ending text of word is def
  • \b - word boundary
like image 108
anubhava Avatar answered Oct 21 '22 01:10

anubhava