Reputation: 1778
I need to validate the EditText value using Regex. The condition:
I have achieved this using two different Pattern but I have no idea to how to check both in single Regex.
I used this following Regex
public boolean validFloatForString(String value) {
String decimalPattern = "([0-9]*)\\.([0-9]*)";
String integerPattern = "([0-9]*)";
boolean match = Pattern.matches(decimalPattern, value)
|| Pattern.matches(integerPattern, value);
System.out.println(match); // if true then decimal else not
return match;
}
Upvotes: 0
Views: 921
Reputation: 1948
Your pattern String decimalPattern = "([0-9]*)\\.([0-9]*)"
will match .
, while integerPattern
will always match. That's because *
means 0 or more.
I would use something like
String pattern = "^([0-9]+(?:\\.[0-9]*)?)";
Which matches unsigned integer and floats.
Edit 1
To match also unsigned floats, beginning with .
String pattern = "\\b([0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)\\b";
I also substitute the ^
, which means beginning of the string to match, with word boundary \\b
.
Upvotes: 1
Reputation: 52185
You could use something like so: ^[0-9]+(\\.[0-9]+)?$
.
The above will make sure that the string is made up from one or more digits which is optionally followed by a decimal point and one or more digits.
Upvotes: 0
Reputation: 851
If you are on Android you could use the embedded validator for this and e.g. set the InputType:
EditText text = new EditText(this);
text.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
Upvotes: 0