[英]Regex in java to find pattern like % from given string
I am a noob to regex. 我是正则表达式的菜鸟。
I have string like:- 我有这样的字符串:
1.9% 2581/candaemon: 0.4% user + 1.4% kernel
and i have to extract all patterns matched with this type % 我必须提取与此类型%相匹配的所有模式
Like:- for given str result should be 像:-对于给定的str结果应该是
matcher.group(0) total 1.9
matcher.group(0) user 0.4
matcher.group(0) kernel 1.5
So far i have tried with this code but no luck :- 到目前为止,我已经尝试过使用此代码,但是没有运气:-
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+"";
}
}
I would go about this by first splitting your input string on %
, and then using a regular expression on each fragment to extract the number you want: 我将首先在%
上分割输入字符串,然后在每个片段上使用正则表达式提取所需的数字,以解决此问题:
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]);
Output: 输出:
total 1.9
user 0.4
kernel 1.4
Here is a link where you can test the regular expression which is being used on each part of the input string: 这是一个链接,您可以在其中测试在输入字符串的每个部分上使用的正则表达式:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.