Regex to split up string of CPU usage without percentage

Viewed 157

Is it possible to get the result just first two digits without % in the first group. Iam using Telegraf with Grafana.

Example:

5 Secs ( 22.3463%) 60 Secs ( 25.677%) 300 Secs ( 21.3522%)

Result:

22

I found out this regex in the similar topic, but it's return bad format for me :

^\s*\d+\s+Secs\s*\(\s*(\d+(?:\.\d+)?%)\)\s+\d+\s+Secs\s+\(\s+(\d+(?:\.\d+)?%)\)\s+\d+\s+Secs\s+\(\s+(\d+(?:\.\d+)?%)\)$
3 Answers

With your shown samples, please try following regex.

^\d+\s+Secs\s+\(\s+(\d+)(?:\.\d+%)?\)(?:\s+\d+\s+Secs\s+\(\s+\d+(?:\.\d+)?%\))*

Online demo for above regex

Explanation: Adding detailed explanation for above.

^\d+\s+Secs\s+\(\s+          ##From starting of value matching digits(1 or more occurrences) followed by space(s) Secs spaces ( spaces.
(\d+)                        ##Creating 1st and only capturing group where we have digits in it.
(?:\.\d+%)?\)                ##In a non-capturing group matching dot digits % ) keeping it optional followed by )
(?:                          ##Creating a non-capturing group here.
   \s+\d+\s+Secs\s+\(\s+\d+  ##matching spaces digits spaces Secs spaces ( spaces digits
   (?:\.\d+)?                ##In a non-capturing group matching dot digits keeping it optional.
   %\)                       ##matching % followed by ) here.
)*                           ##Closing very first non-capturing group, and matching its 0 or more occurrences.

You can update your pattern to use a single capturing group by relocating the parenthesis around the digits only for the first occurrence.

You can omit the second and third capture groups as you don't need them.

^\s*\d+\s+Secs\s*\(\s*(\d+)(?:\.\d+)?%\)\s+\d+\s+Secs\s+\(\s+\d+(?:\.\d+)?%\)\s+\d+\s+Secs\s+\(\s+\d+(?:\.\d+)?%\)$

                      ^   ^

Regex demo

Or you might use a named capture group, for example digits

^\s*\d+\s+Secs\s*\(\s*(?P<digits>\d+)(?:\.\d+)?%\)\s+\d+\s+Secs\s+\(\s+\d+(?:\.\d+)?%\)\s+\d+\s+Secs\s+\(\s+\d+(?:\.\d+)?%\)$

If it's just the 1st occurrence you're after, wouldn't the following work?

/secs\s*\(\s*(\d+)/i
Related