Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading