Matching numbers with regular expressions — only digits and commas

.net, matching, numbers, regex

Solution

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 */
}

Problem

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?

Original source

Related problems