【问题标题】:Get Float OR integer value from the String in java从java中的字符串获取浮点或整数值
【发布时间】:2014-03-26 06:13:27
【问题描述】:

我正在尝试从字符串中获取浮点数或整数。 因为这是我的测试用例..

1) str="IN100RINR"               Output = 100;
2) str="IN100RINR"               Output = 100;
3) str="100INR"                  Output = 100;
4) str="100.50INR"               Output = 100.50;
5) str="IN100.50R"               Output = 100.50;
6) str="INR100.50"               Output = 100.50;
7) str="INR100INRINR20.500INR"   Output = 100 

这一切都在我的程序中工作,但案例 7 不工作..它返回 100.500

这是我的代码...

          Pattern pattern = Pattern.compile("(\\d+)");
    String str="INR100INRINR20.500INR", amount="", decimal="";
    if(str.contains(".")){
        String temp= str.substring(str.indexOf(".")+1); 
        Matcher matcher = pattern.matcher(temp);
        if(matcher.find()){
            decimal = matcher.group();
        }
    }
          Matcher matcher = pattern.matcher(str);
    if(matcher.find()){
        if(decimal != ""){
            amount=matcher.group()+"."+decimal;
        }else{
            amount = matcher.group();
        }

      System.out.println(Float.valueOf(amount));
    }

【问题讨论】:

  • 那么你希望它返回什么?
  • 您正在查找小数点后的值并将其添加到您最初找到的 \d,这就是您得到 100.500 的原因。

标签: java regex string string-parsing


【解决方案1】:

您可以使用简单的匹配器/查找方法来执行类似的操作:

Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?"); // Match int or float
String str="INR100INRINR20.500INR";
Matcher matcher = pattern.matcher(str);
if(matcher.find()){
    System.out.println(matcher.group());
}

ideone demo

【讨论】:

  • 感谢您的回答...现在,如果我需要字符串中的所有数字浮点或整数,例如.. Str = INR100INR20.500INR300 输出,例如:100 20.500 300 因为它只返回第一个值所以..
  • 如果你需要only 100,上面的代码就是这样做的。如果您同时需要10020.500,则使用while 循环:while(matcher.find()) 而不是if
猜你喜欢
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多