javascriptregex

How to stop positive lookbehind from going too far behind


Expression:

(?<=d)(.*?)(?=but) 

catches:

og1 dog2 

from string:

"adog1 dog2 but"

What changes should I make make to the expression to catch only

og2 

Solution

  • You could use this regex:

    (?<=d)([^d]*)(?=but)
    

    The change I have made is the middle component:

    ([^d]*)
    

    This ensures that we don't cross another letter d before asserting that but follows. This means that the match will be the last d before but.

    Demo