Search code examples
regexpcre2

Regex rule stop capturing when specific word is find


I'm working with regex on PRCE2 environment.

When I perform a capture group, I know perfectly how to stop when I find a specific character. For example: if I have following log portion:

logger=CGP  spid=5116

I know I can capture the logger value and save it as "logger" with:

logger\=(?<logger>[^\s]+)

That means: start capture after = and stop when you ecounter a space. But what about if I want order: stop when a specific word is met?

For example, if I have:

msg=Reject access   logger=CGP

If I want capture msg field value, I cannot use a space as stop character: first space must be included. I must stop when logger word is encountered.

How to achieve this?


Solution

  • You may use it like this with a following lookahead:

    \bmsg=(?<logger>.+?)(?=\h+logger=)
    

    RegEx Demo

    RegEx Details:

    • \bmsg: Match word msg
    • =: Match =
    • (?<logger>.+?): Capture group logger that match 1+ of any character (lazy match)
    • (?=\h+logger=): Lookahead to assert that we have 1+ whitespaces followed by logger= text ahead of the current position