Reputation: 273
I have one text input.
I wrote a regex for masking all special characters except .
and -
. Now if by mistake the user enters two .
(dots) in input, then with the current regex
var valueTest='225..36'
valueTest.match(/[^-.\d]/)
I expected that the number will not pass this condition
How to handle this case. I just want one .
(dot) in input field since it is a number.
Upvotes: 6
Views: 22139
Reputation: 174874
I think you mean this,
^-?\d+(?:\.\d+)?$
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.Upvotes: 12
Reputation: 3188
if you just want to handle number ,you can try this:
valueTest.match(/^-?\d+(\.\d+)?$/)
Upvotes: 3
Reputation: 48444
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.
Upvotes: 2