从java中的String获取Float OR整数值

时间:2014-03-26 06:13:27

标签: java regex string string-parsing

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

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));
    }

1 个答案:

答案 0 :(得分:11)

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

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