我是一個正則表達式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+"";
}
}
非常棒,整潔乾淨。謝謝:) –
不錯的解決方案Tim ... –