Java searching float number in String

前端 未结 7 2053
轻奢々
轻奢々 2020-12-02 02:35

let\'s say i have string like that:

eXamPLestring>1.67>>ReSTOfString

my task is to extract only 1.67 from string above.

7条回答
  •  [愿得一人]
    2020-12-02 03:25

    Have a look at this link, they also explain a few things that you need to keep in mind when building such a regex.

    [-+]?[0-9]*\.?[0-9]+

    example code:

    String[] strings = new String[3];
    
        strings[0] = "eXamPLestring>1.67>>ReSTOfString";
        strings[1] = "eXamPLestring>0.57>>ReSTOfString";
        strings[2] = "eXamPLestring>2547.758>>ReSTOfString";
    
        Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
    
        for (String string : strings)
        {
            Matcher matcher = pattern.matcher(string);
            while(matcher.find()){
                System.out.println("# float value: " + matcher.group());
            }
        }
    

    output:

    # float value: 1.67
    # float value: 0.57
    # float value: 2547.758
    

提交回复
热议问题