2016-06-21 97 views
-1

我有一個字符串,它看起來像這樣:在正則表達式查詢返回的特定值匹配

5 Secs (14.2725%) 60 Secs (12.630%) 300 Secs (15.5993%) 

使用(\d{2}[.]\d{3}),我可以匹配我想要的值;但是,我只需要一個查詢的值爲1,另一個查詢的值爲2,第三個值爲3。這是監控系統的一部分,因此必須使用單一的正則表達式來完成,我沒有訪問其他shell工具可以使這一點變得簡單。

+1

什麼是你真正想從你給的例子中提取?順便說一句,我認爲你將需要擺脫你提到的正則表達式中的一堆東西。 –

+3

幾乎沒有關於什麼編程語言或shell的信息。另外,如果你有一個shell,爲什麼你說「我沒有訪問其他shell工具」?通常在系統上安裝大量的shell工具。也許你可以填寫我們的細節? – Kusalananda

+0

一個幾乎相同的問題:http://stackoverflow.com/questions/37924545/return-the-next-nth-result-w-after-a-hyphen-globally/37924922#37924922 –

回答

0

說明
^(?:[^(]*\([^)]*\)){2}[^(]*\(\s*\K[0-9]{2}[.][0-9]{3} 
        ^^^ 

Regular expression visualization

{2}的數量可以根據需要而改變,然後將表達將選擇該串中的N + 1%的值。如果選擇0,那麼表達式將匹配第一個百分比,如果您選擇1則表達式將匹配第二個百分比...等等。

該表達式假設語言支持\K正則表達式命令,該命令強制引擎刪除與之相匹配的所有內容,直到\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) 
----------------------------------------------------------------------