Search code examples
regexpcre

Look back and stop on the first one


I'm trying to solve this problem with a regular expression :

1A2TestB

Retrieve what's between 2 and B knowing that B is fixed and known, 2 is the first digit backwards which should give me Test

Is there a simple way (a secret symbol) to do this?

I thought I could do it with the Lookbehind

(?<=\d)(.*?)B

but no matter how hard I try, I can't get what I want.


Solution

  • You may use

    \D*?(?=B)
    

    Or, to avoid empty results:

    \D+?(?=B)
    

    Details

    • \D*? - 0 or more chars other than digits, as few as possible
    • \D+? - 1 or more chars other than digits, as few as possible
    • (?=B) - a position in the string that is immediately followed with B

    See the regex demo