2016-01-20 18 views
2

我是一個正則表達式noob。在java中的正則表達式像從給定的字符串%%發現模式

我有串,如: -

1.9% 2581/candaemon: 0.4% user + 1.4% kernel 

,我要提取這種類型的

像匹配的所有模式: - 對於給定的STR結果應該是

matcher.group(0) total 1.9 
matcher.group(0) user 0.4 
matcher.group(0) kernel 1.5 

到目前爲止,我已嘗試使用此代碼,但沒有運氣: -

while ((_temp = in.readLine()) != null) 
       { 
        if(_temp.contains("candaemon")) 
        { 
         double total = 0, user = 0, kernel = 0, iowait = 0; 

         //Pattern regex = Pattern.compile("(\\d+(?:\\%\\d+)?)"); 
         Pattern regex = Pattern.compile("(?<=\\%\\d)\\%"); 
         Matcher matcher = regex.matcher(_temp); 

         int i = 0; 
         while(matcher.find()) 
         { 
          System.out.println("MonitorThreadCPULoad _temp "+_temp+" and I is "+i); 
          if(i == 0) 
          { 
           total = Double.parseDouble(matcher.group(0)); 
           System.out.println("matcher.group(0) total "+total); 
          } 
          if(i == 1) 
          { 
           user = Double.parseDouble(matcher.group(0)); 
           System.out.println("matcher.group(0) user "+user); 
          } 
          if(i == 2) 
          { 
           kernel = Double.parseDouble(matcher.group(0)); 
           System.out.println("matcher.group(0) kernel "+kernel); 
          }  
          i++; 
         } 

         System.out.println("total "+total+" user"+user+" kernel"+kernel+" count"+count); 
         System.out.println("cpuDataDump[count] "+cpuDataDump[count]); 
         cpuDataDump[count] = total+""; 
         cpuDataDump[(count+1)] = user+""; 
         cpuDataDump[(count+2)] = kernel+""; 
        } 
       } 

回答

2

我會去這個由第一剖開你的輸入字符串上%,然後使用正則表達式的每個片段提取號碼你想要的:

String input = "1.9% 2581/candaemon: 0.4% user + 1.4% kernel"; 
String[] theParts = input.split("\\%"); 
for (int i=0; i < theParts.length; ++i) { 
    theParts[i] = theParts[i].replaceAll("(.*)\\s([0-9\\.]*)", "$2"); 
} 

System.out.println("total " + theParts[0]); 
System.out.println("user " + theParts[1]); 
System.out.println("kernel " + theParts[2]); 

輸出:

total 1.9 
user 0.4 
kernel 1.4 

這裏是一個鏈接,可以測試正被輸入字符串的每一個部分中使用的正則表達式:

Regex101

+1

非常棒,整潔乾淨。謝謝:) –

+1

不錯的解決方案Tim ... –

2

你可以測試(.. [0-9])\%這個模式。試試你的字符串,找到正則表達式側適當模式 - >regex

+0

是的這似乎是完美的一個,因爲我檢查給你的鏈接由你。但我無法將其設置爲模式Pattern regex = Pattern.compile(「(.. [0-9])\%」);它給我錯誤「無效的轉義序列(有效的是\ b \ t \ n \ f \ r \」\'\\)「 –

+0

試圖把它放在正則表達式創建適當的模式。我相信它會工作。 .....謝謝。 –

相關問題