I have this expression for valid number only…
^[0-9,-\.]+$
This works fine, but I need to ensure that a maximum of 1 , and 1 . can be entered? This needs to cater for different cultures so it doesn’t matter to me which order the , and . come in.
Can anyone help with this?
If your regex flavor supports lookaheads you can use:
If not, then you could do something like this:
But I find this is rather ugly.
Note that I changed your character class.
[0-9]can be shortened to\d(note that dependent on your regex flavor this might match other Unicode digits than just0-9),.does not need to be escaped inside character classes, and-belong at the beginning or the end of character class, otherwise they need to be escaped. Funnily enough, in your case it does not even make a difference, because,-.creates a range of characters from,to.(in ASCII order). However all the characters in this range are incidentally,,-and.. Lucky you 😉However, both answers really just do what you are explicitly asking for. Your pattern will still match
--.--34,---1--2and stuff like that. If you really want to match a valid number with culture-independent decimal point you should probably use this instead:Of if you want to match a valid number with
.decimal point and at most one,thousand-separator (or vice-versa), this:I don’t think there is a shorter version, really. Do not worry about all the
?:. They just make the subpatterns non-capturing. Since you do not need that anyway, it is usually a significant performance increase.