我有一个看起来像这样的字符串:
5 Secs ( 14.2725% ) 60 Secs ( 12.630% ) 300 Secs ( 15.5993% )
使用(\d{2}[.]\d{3})
,我可以匹配我想要的值;但是,我只需要在一个查询中获得值1,在另一个查询中需要值2,在第三个查询中需要值3。这是监控系统的一部分,因此必须使用一行正则表达式,我无法访问其他可以轻松实现的shell工具。
答案 0 :(得分:0)
^(?:[^(]*\([^)]*\)){2}[^(]*\(\s*\K[0-9]{2}[.][0-9]{3}
^^^
{2}
中的数字可以根据需要更改,然后表达式将选择字符串中的N + 1%值。如果您选择0
,那么表达式将匹配第一个百分比,如果您选择1
,则表达式将匹配第二个百分比......依此类推。
此表达式假定该语言支持\K
regex命令,该命令强制引擎删除与\K
匹配的所有内容。
现场演示
https://regex101.com/r/oX0mJ4/1
示例文字
5 Secs ( 14.2725% ) 60 Secs ( 12.630% ) 300 Secs ( 15.5993% )
样本匹配
使用所写的表达式返回第3个条目。
15.599
NODE EXPLANATION
----------------------------------------------------------------------
^ the beginning of a "line"
----------------------------------------------------------------------
(?: group, but do not capture (2 times):
----------------------------------------------------------------------
[^(]* any character except: '(' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
\( '('
----------------------------------------------------------------------
[^)]* any character except: ')' (0 or more
times (matching the most amount
possible))
----------------------------------------------------------------------
\) ')'
----------------------------------------------------------------------
){2} end of grouping
----------------------------------------------------------------------
[^(]* any character except: '(' (0 or more times
(matching the most amount possible))
----------------------------------------------------------------------
\( '('
----------------------------------------------------------------------
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times (matching the most amount
possible))
----------------------------------------------------------------------
\K 'K'
----------------------------------------------------------------------
[0-9]{2} any character of: '0' to '9' (2 times)
----------------------------------------------------------------------
[.] any character of: '.'
----------------------------------------------------------------------
[0-9]{3} any character of: '0' to '9' (3 times)
----------------------------------------------------------------------