Java searching float number in String

前端 未结 7 2056
轻奢々
轻奢々 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:11

    /**
     * Extracts the first number out of a text.
     * Works for 1.000,1 and also for 1,000.1 returning 1000.1 (1000 plus 1 decimal).
     * When only a , or a . is used it is assumed as the float separator.
     *
     * @param sample The sample text.
     *
     * @return A float representation of the number.
     */
    static public Float extractFloat(String sample) {
        Pattern pattern = Pattern.compile("[\\d.,]+");
        Matcher matcher = pattern.matcher(sample);
        if (!matcher.find()) {
            return null;
        }
    
        String floatStr = matcher.group();
    
        if (floatStr.matches("\\d+,+\\d+")) {
            floatStr = floatStr.replaceAll(",+", ".");
    
        } else if (floatStr.matches("\\d+\\.+\\d+")) {
            floatStr = floatStr.replaceAll("\\.\\.+", ".");
    
        } else if (floatStr.matches("(\\d+\\.+)+\\d+(,+\\d+)?")) {
            floatStr = floatStr.replaceAll("\\.+", "").replaceAll(",+", ".");
    
        } else if (floatStr.matches("(\\d+,+)+\\d+(.+\\d+)?")) {
            floatStr = floatStr.replaceAll(",", "").replaceAll("\\.\\.+", ".");
        }
    
        try {
            return new Float(floatStr);
        } catch (NumberFormatException ex) {
            throw new AssertionError("Unexpected non float text: " + floatStr);
        }
    }
    

提交回复
热议问题