mrmiz
mrmiz

Reputation: 3

PCRE Regex Matching Patterns until next pattern is found

I'm struggling to find a solution to this regex which appears to be fairly straight forward. I need to match a pattern that precedes another matching pattern.

I need to capture the "Mean:" that follows "Keberos-wsfed" in the following:

Kerberos:
  Historical:
   Between 26 and 50 milliseconds: 10262
   Between 50 and 100 milliseconds: 658
   Between 101 and 200 milliseconds: 9406
   Between 201 and 500 milliseconds: 6046
   Between 501 milliseconds and 1 second: 1646
   Between 1 and 5 seconds: 1399
   Between 6 and 10 seconds: 13
   Between 11 and 30 seconds: 34
   Between 31 seconds and 1 minute: 7
   Between 1 minute and 2 minutes: 1
   Mean: 268, Mode: 36, Median: 123
   Total: 29472
 Kerberos-wsfed:
  Historical:
   Between 26 and 50 milliseconds: 3151
   Between 50 and 100 milliseconds: 129
   Between 101 and 200 milliseconds: 650
   Between 201 and 500 milliseconds: 411
   Between 501 milliseconds and 1 second: 171
   Between 1 and 5 seconds: 119
   Between 6 and 10 seconds: 4
   Between 11 and 30 seconds: 6
   Between 1 minute and 2 minutes: 1
   Mean: 176, Mode: 33, Median: 37
   Total: 4642

I can match (?:Kerberos-wsfed:), I can match Mean: but I must find the value of Mean after Kerberos-wsfed but having difficulty. Thanks for the assistance.

Upvotes: 0

Views: 60

Answers (3)

degant
degant

Reputation: 4981

Using capturing group:

Kerberos-wsfed:[\s\S]*Mean:\s(\d+)
  • Kerberos-wsfed: matches the literal as-is
  • [\s\S]* allows any number of characters between (including line delimitters)
  • Mean:\s matches the literal Mean followed by a space \s
  • Finally (\d+) which is wrapped in the first capturing group captures the value you are looking for. It essentially allows any number of digits

Regex 101 Demo

The value that you are looking for (176) will be in the first capturing group which is $1 or the first one based on your language. For instance, in PHP:

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

echo $matches[0][1];
// Output: 176

Upvotes: 0

Sergey Khalitov
Sergey Khalitov

Reputation: 1027

Try to use that regular expresion: #Kerberos-wsfed:.+?Mean:\s+(\d+)#s

You can use just space or \s instead of \s+ if you're shure in file format.

Value 176 will be at group 1 of matched elements

Demo: https://regex101.com/r/gwkUPJ/1

Upvotes: 0

logi-kal
logi-kal

Reputation: 7880

Use the regex

Kerberos-wsfed[\s\S]*?Mean: *(\d+)

The mean value is contained in the capturing group 1, that is $1 or \1 depending on your programming language.

See demo.

Upvotes: 2

Related Questions