Home > Mobile >  How can I check the given pattern into an input dialog?
How can I check the given pattern into an input dialog?

Time:03-16

I have an input dialog and I want to check if user typed a specific pattern. For example, user can type any number - and any number. Something like this 10-20. How can I check if user typed this kind of pattern?

CodePudding user response:

Assuming the numbers are guaranteed to be positive integers, @Eritrean's suggestion is correct.

String input = "10-20";
String regex = "\\d -\\d ";
System.out.println("Input is valid? "   input.matches(regex));

For the current input, it will print out that the input is valid ("true") because it matched the given regular expression. An input like 10-A0 would not be valid and thus, will print out "false".

If the input is not guaranteed to be a positive integer, these are my suggestions accordingly:

  1. For signed values, add [- ]? in front of each digit pattern: [- ]?\\d -\\d [- ]?. This will match signed integers by allowing optional sign characters in front of the number.
  2. For floating-point numbers, I suggest \\d*\\.?\\d . This regular expression expects the numeric value to have optional digits before the decimal point, and an unbounded number of digits after. It also matches integer values as well. So, a regular expression like \\d*\\.?\\d -\\d*\\.?\\d , should be able to account for integers and floating-point numbers separated by a dash. If you require signed floating point numbers, follow suggestion in #1 above.

CodePudding user response:

To check if the input is correct do this:

in Java:

Pattern pattern = Pattern.compile("^[0-9] -[0-9] ",Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("10-20");
boolean matchFound = matcher.find();
if(matchFound) {
  System.out.println("Match found");
} else {
  System.out.println("Match not found");
}
  • Related