java中的正则表达式从给定的字符串中找到类似%的模式

时间:2016-01-20 05:28:14

标签: java regex

我是正则表达式的菜鸟。

我的字符串如下: -

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 个答案:

答案 0 :(得分:2)

您可以测试(.. [0-9])\%此模式。尝试使用字符串在Regex端找到合适的模式 - &gt; regex

答案 1 :(得分: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