regex look ahead quantifier

Viewed 66

I want to match the last b that is preceded by aa from the string ababaaabaab.

My regex: (?<=a{2})b

But it matches the third b which is preceded by aaa.

I am a beginner.

1 Answers

Use

(?<=(?<!a)a{2})b

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  (?<=                     look behind to see if there is:
--------------------------------------------------------------------------------
    (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
      a                        'a'
--------------------------------------------------------------------------------
    )                        end of look-behind
--------------------------------------------------------------------------------
    a{2}                     'a' (2 times)
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  b                        'b'
Related