Regex to allow only a single dot in a textbox

前端 未结 4 1276
执念已碎
执念已碎 2020-12-16 06:19

I have one text input.

I wrote a regex for masking all special characters except . and -. Now if by mistake the user enters two .

4条回答
  •  不思量自难忘°
    2020-12-16 06:41

    You can probably avoid regex altogether with this case.

    For instance

    String[] input = { "225.36", "225..36","-225.36", "-225..36" };
    for (String s : input) {
        try {
            Double d = Double.parseDouble(s);
            System.out.printf("\"%s\" is a number.%n", s);
        }
        catch (NumberFormatException nfe) {
            System.out.printf("\"%s\" is not a valid number.%n", s);
        }
    }
    

    Output

    "225.36" is a number.
    "225..36" is not a valid number.
    "-225.36" is a number.
    "-225..36" is not a valid number.
    

提交回复
热议问题