Regex to allow only a single dot in a textbox

前端 未结 4 1263
执念已碎
执念已碎 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:24

    if you just want to handle number ,you can try this:

    valueTest.match(/^-?\d+(\.\d+)?$/)
    
    0 讨论(0)
  • 2020-12-16 06:28

    I think you mean this,

    ^-?\d+(?:\.\d+)?$
    

    DEMO

    It allows positive and negative numbers with or without decimal points.

    EXplanation:

    • ^ Asserts that we are at the start.
    • -? Optional - symbol.
    • \d+ Matches one or more numbers.
    • (?: start of non-capturing group.
    • \. Matches a literal dot.
    • \d+ Matches one or more numbers.
    • ? Makes the whole non-capturing group as optional.
    • $ Asserts that we are at the end.
    0 讨论(0)
  • 2020-12-16 06:39

    Use below reg ex it will meet your requirements.

    /^\d+(.\d+)?$/

    0 讨论(0)
  • 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.
    
    0 讨论(0)
提交回复
热议问题