正则表达式拆分 CPU 不带百分比的用法字符串

Regex to split up string of CPU usage without percentage

是否可以在第一组中不带 % 的情况下仅获取前两位数字的结果。我正在将 Telegraf 与 Grafana 结合使用。

示例:

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

结果:

22

我在类似的主题中发现了这个正则表达式,但它 return 对我来说格式不对 :

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

使用您展示的示例,请尝试使用正则表达式。

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

Online demo for above regex

解释: 为以上添加详细解释。

^\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.

您可以更新您的模式以使用单个捕获组,方法是仅在第一次出现时重新定位数字周围的括号。

您可以省略第二个和第三个捕获组,因为您不需要它们。

^\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

或者您可以使用命名的捕获组,例如 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+)?%\)$

如果这只是您所追求的第 1 次出现,那么下面的方法行不通吗?

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