Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从java中的字符串中获取浮点值或整数值_Java_Regex_String_String Parsing - Fatal编程技术网

从java中的字符串中获取浮点值或整数值

从java中的字符串中获取浮点值或整数值,java,regex,string,string-parsing,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"

我试图从字符串中获取浮点或整数。 这是我的测试用例

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

您可以使用一个简单的matcher/find方法执行以下操作:

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

您可以使用一个简单的matcher/find方法来执行以下操作:

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

那么,您希望它返回什么?您正在查找小数点后的值,并将其添加到最初找到的
\d
中,这就是为什么您得到
100.500
。那么您希望它返回什么?您正在查找小数点后的值,并将其添加到最初找到的
\d
中,这就是为什么您需要返回的原因正在获取
100.500
。感谢您的回答。。。现在如果我需要字符串中的所有数字,比如。。Str=inr100inr20.500INR300输出类似于:100 20.500 300,因为is只返回我的第一个值,所以..如果您只需要100,上面的代码就会这样做。如果您同时需要
100
20.500
,请使用
while
循环:
while(matcher.find())
,而不是
If
。谢谢您的回答。。。现在如果我需要字符串中的所有数字,比如。。Str=inr100inr20.500INR300输出类似于:100 20.500 300,因为is只返回我的第一个值,所以..如果您只需要100,上面的代码就会这样做。如果同时需要
100
20.500
,则使用
while
循环:
while(matcher.find())
,而不是
If