Search code examples
regexregex-lookarounds

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


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.


Solution

  • 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.