gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:55:50 26 4
gpt4 key购买 nike

我是正则表达式的菜鸟。

我有这样的字符串:-

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

最佳答案

我会先在 % 上拆分您的输入字符串,然后在每个片段上使用正则表达式来提取您想要的数字:

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

关于java - java中的正则表达式从给定字符串中查找类似%的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34892194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com