Question

i'm trying to get float or integer from the string. for that here is my test cases..

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 

This all working in my program but case 7 is not working..it returns 100.500

here is my code...

          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));
    }
Was it helpful?

Solution

You could use a simple matcher/find method to do something like that:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top