Home > Mobile >  regex to capture string A if there is not string B before next occurrence of string A
regex to capture string A if there is not string B before next occurrence of string A

Time:06-29

I want to grab text A if there is no text B between it and next occurence of A. For example, those ones would match

A something A something B
^
AAAB
^^
ABAAB
  ^
A B A something
    ^

Is it even possible to do? I can't think of any way to do it

CodePudding user response:

You can use look ahead:

A(?=(?:(?!B).)*(?:A|$))

Or with negative look ahead:

A(?!(?:(?!A).)*B)

This will work also when A or B are multi-character strings.

CodePudding user response:

You may want the following regex:

A(?![^Aa]*B)

It will match any "A" which is not followed by any character other than a "B".

Check the demo here.

  • Related