Java字符串操作:根据模式从字符串中提取整数和浮点数 [英] Java String Manipulation: extracting integer and float from string based on pattern

查看:193
本文介绍了Java字符串操作:根据模式从字符串中提取整数和浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个可能的内容的字符串。
显然金额总是不同,我想提取关键信息和

 情况0:pricesString = 
情况1:pricesString =$ 0.023
情况2:pricesString =10+:$ 1.46 100+:$ 0.16 500+:$ 0.04
$ b $ Case 0 我不想做任何事情。



<



 文章。 addPrice(1,0.023); 

个案2 我想执行:

  article.addPrice(10,1.46); 
article.addPrice(100,0.16);
article.addPrice(500,0.04);

如何提取这些信息,以便可以调用article.addPrice,其中包含float和integer值

解决方案

这看起来像是一个正则表达式的工作:

<$ p $字符串pricesString =10+:$ 1.46 100+:$ 0.16 500+:$ 0.04;
Pattern p = Pattern.compile((\\d +)\\ +:\\ $(\\\\\\\\\\\\\\\ d));
Matcher m = p.matcher(pricesString);
while(m.find()){
Intger.parseInt(m.group(1));
Double.parseDouble(m.group(2));



$ b您可以通过简单的 .length()检查。上面的代码是最后一种情况。剩下的就是eaiser

I have the following two possible contents of a String. Obviously the amounts always vary and I would like to extract the key information and

Case 0:   pricesString = ""
Case 1:   pricesString = "$0.023"
Case 2:   pricesString = "10+: $1.46 100+: $0.16 500+: $0.04"

In Case 0 I would like to do nothing.

In Case 1 I would like to perform:

article.addPrice(1, 0.023);

In Case 2 I would like to perform:

article.addPrice(10, 1.46);
article.addPrice(100, 0.16);
article.addPrice(500, 0.04);

How can I extract this information so I can can call article.addPrice with the float and integer values contained?

解决方案

That looks like a job for regex:

String pricesString = "10+: $1.46 100+: $0.16 500+: $0.04";
Pattern p = Pattern.compile("(\\d+)\\+: \\$(\\d\\.\\d\\d)");
Matcher m = p.matcher(pricesString);
while (m.find()) {
    Intger.parseInt(m.group(1));
    Double.parseDouble(m.group(2));
}

You can choose between the 3 cases by a simple .length() check. The code above is for the last case. The rest is eaiser

这篇关于Java字符串操作:根据模式从字符串中提取整数和浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆