如何从字符串在Java中使用正则表达式解析浮点值浮点、字符串、正则表达式、Java

2023-09-07 22:13:47 作者:风清月明

我想从

CallCost:Rs.13.04 Duration:00:00:02 Bal:Rs.14.67 2016 mein Promotion

从上面的字符串,我需要13.04和14.67。我用正则表达式如下

From above string i need 13.04 and 14.67. I used following regex

  Pattern p = Pattern.compile("\\d*\\.\\d+");
  Matcher m = p.matcher(s);
  while (m.find()) {
  System.out.println(">> " + m.group());
            }

但是使用这个我得到。13,0.04,。14,0.67在此先感谢

But using this i am getting ".13", ".04", ".14", ".67" Thanks in advance

推荐答案

使用 \\\\ D + 而不是 \\\\ D *

 Pattern p = Pattern.compile("\\d+\\.\\d+");

为什么呢?

由于如果你使用 \\\\ D * \\\\ \\\\ D + ,这应该从点匹配旁边存在 RS ,因为你所做的整数部分重复零次或多次,因此,它不关心的整数部分。

Because if you use \\d*\\.\\d+, this should match from the dot exists next to Rs, since you made the integer part to repeat zero or more times., So it don't care about the integer part.

演​​示