I have one text input.
I wrote a regex for masking all special characters except .
and -
. Now if by mistake the user enters two .
if you just want to handle number ,you can try this:
valueTest.match(/^-?\d+(\.\d+)?$/)
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.Use below reg ex it will meet your requirements.
/^\d+(.\d+)?$/
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.