Search code examples
regexregex-greedy

ReGex, How to find second instance of string


If I want to get the Name between “for” and “;” which is NISHER HOSE, can you help me find the correct regex expression as there is more than one "for’ and “;” in the string

Data Owner Approval Needed for Access Request #: 2137352 for NISHER HOSE; CONTRACTOR; Manager: MUILLER, TIM (TWM0069)

Using the regular expression (?<=for).*(?=;) I get the wrong match Access Request #: 2137352 for NISHER HOSE; CONTRACTOR - see screenshot on https://www.regextester.com/

Thanks


Solution

  • If you only want to assert for on the left, you should and make sure to not match for again and you should exclude matching a ; while asserting there is one at the right.

    (?<=\bfor )(?:(?!\bfor\b)[^;])+(?=;)
    

    Explanation

    • (?<=\bfor ) Assert for at the left
    • (?:(?!\bfor\b)[^;])! Match 1+ times any char except ; if from the current position not directly followed by for surrounded by word boundaries
    • (?=;) Assert ; directly at the right

    Regex demo