【问题标题】:Regex to split up string of CPU usage without percentage正则表达式拆分 CPU 使用率字符串,没有百分比
【发布时间】:2021-09-01 23:05:27
【问题描述】:

是否可以在第一组中仅获得前两位数而没有 % 的结果。我正在将 Telegraf 与 Grafana 一起使用。

例子:

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

结果:

22

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

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

【问题讨论】:

  • 您使用的是什么正则表达式变体(python、javascript、某些特定软件)?在每种情况下,分组的工作方式以及回顾和参考等其他功能都有很大不同

标签: regex grafana telegraf


【解决方案1】:

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

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

^\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+)?%\)$

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果这只是您所追求的第一次出现,那么以下方法不起作用吗?

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-26
        • 1970-01-01
        • 2017-02-23
        相关资源
        最近更新 更多