Capture number if string contains "X", but limit match (cannot use groups)

Viewed 85

I need to extract numbers like 2.268 out of strings that contain the word output:

Approxmiate output size of output: 2.268 kilobytes

But ignore it in strings that don't:

some entirely different string: 2.268 kilobytes

This regex:

(?:output.+?)([\d\.]+)

Gives me a match with 1 group, with the group being 2.268 for the target string. But since I'm not using a programming language but rather CloudWatch Log Insights, I need a way to only match the number itself without using groups.

I could use a positive lookbehind ?<= in order to not consume the string at all, but then I don't know how to throw away size of output: without using .+, which positive lookbehind doesn't allow.

2 Answers

With your shown samples, please try following regex.

output:\D+\K\d(?:\.\d+)?

Online demo for above regex

Explanation: Adding detailed explanation for above.

output:\D+    ##Matching output colon followed by non-digits(1 or more occurrences)
\K            ##\K to forget previous matched values to make sure we get only further matched values in this expression.
\d(?:\.\d+)?  ##Matching digit followed by optional dot digits.

Since you are using PCRE, you can use

output.*?\K\d[\d.]*

See the regex demo. This matches

  • output - a fixed string
  • .*? - any zero or more chars other than line break chars, as few as possible
  • \K - match reset operator that removes all text matched so far from the overall match memory buffer
  • \d - a digit
  • [\d.]* - zero or more digits or periods.
Related