Search code examples
regexpcre

Positive Lookbehind Regex


Let's say I have the follow String:

"TEST="test123; xyz=testtest"|PATH="testCookie=1234;"|COOKIE="testCookie2=4321; testCookie=1234;"

I need to write a Regex to only select the testCookie=1234; in the COOKIE="" Field. I tried it with positive lookbehind (?<=COOKIE=") but the problem is my target isn't always on the first position after the (?<=COOKIE=")

Can anyone help me with this regex?


Solution

  • As the value is between the double quotes after COOKIE=" and you tagged pcre:

    \bCOOKIE="[^"]*\K\btestCookie=[^;"]*;
    

    Explanation

    • \bCOOKIE=" Match the word COOKIE followed by =
    • [^"]* Match optional chars other than "
    • \K Forget what is matched so far
    • \btestCookie= Match the word testCookie followed by =
    • [^;"]* Match optional chars other than ; and "
    • ; Match literally

    See a regex101 demo.


    To get separate matches after COOKIE="

    (?:\bCOOKIE="|\G(?!^))[^"]*?\KtestCookie\d+=[^"=;]*[;"]
    

    Explanation

    • (?: Non capture group
      • \bCOOKIE=" Match COOKIE=
      • | Or
      • \G(?!^) Assert the current position at the end of the previous match, not at the start of the string
    • ) Close the non capture group
    • [^"]*? Optionally match as few as possible chars except "
    • \K Reset the starting point of the reported match (clear the match buffer)
    • testCookie\d+= Match testCookie 1+ digits and =
    • [^"=;]*[;"] Optionally match any char except " = ; and then match ; or "

    See another regex demo.