Matching numbers with regular expressions — only digits and commas

前端 未结 10 1617
旧时难觅i
旧时难觅i 2020-11-22 08:07

I can\'t figure out how to construct a regex for the example values:

123,456,789
-12,34
1234
-8

Could you help me?

10条回答
  •  失恋的感觉
    2020-11-22 08:34

    If you only want to allow digits and commas, ^[-,0-9]+$ is your regex. If you also want to allow spaces, use ^[-,0-9 ]+$.

    However, if you want to allow proper numbers, better go with something like this:

    ^([-+] ?)?[0-9]+(,[0-9]+)?$
    

    or simply use .net's number parser (for the various NumberStyles, see MSDN):

    try {
        double.Parse(yourString, NumberStyle.Number);
    }
    catch(FormatException ex) {
        /* Number is not in an accepted format */
    }
    

提交回复
热议问题