Regex rule stop capturing when specific word is find

31 views Asked by At

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?

2

There are 2 answers

2
anubhava On BEST ANSWER

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
1
tahzibi.jafar On

If I understand correctly, msg\=(.*)(logger=).* pattern will OK. you should get first capturing group