Search code examples
regexregex-lookaroundsgoogle-cloud-logging

Regex Get number in Predictable String with *One* Capturing group


GCP Logging (Log Based Metrics) regex requires that I only use 1 capturing group for my Regex Filter, as a result, I can't use the look ahead and behind's that I would prefer. How can I get the number after KeyOne:?

Log: KeyOne:32|KeyTwo:0|KeyThree:|Language:english

Desired Capture: 32

If I were allowed multiple capturing groups, this would work: (?<=KeyOne:)([0-9]+)(?=|)

Is there any way to do this with one Capturing Group?


Solution

  • What you want to do can be done exactly with a single capturing group without lookarounds because the regex is handled with a function that returns only the captured substring if the capturing group is defined in the pattern.

    In your case, you may simply convert non-consuming pattern parts to consuming patterns:

    KeyOne:([0-9]+)\|
    KeyOne:([0-9]+)
    

    Note you only need \| at the end if you only want the match to occur when there is a | char following the number.