簡體   English   中英

Java中的正則表達式從給定的字符串中找到類似%的模式

[英]Regex in java to find pattern like % from given string

我是正則表達式的菜鳥。

我有這樣的字符串:

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+"";
                    }
                }

您可以測試(.. [0-9])\\%此模式。 嘗試您的字符串在正則表達式方面找到適當的模式-> 正則表達式

我將首先在%上分割輸入字符串,然后在每個片段上使用正則表達式提取所需的數字,以解決此問題:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM