1

I am trying to set requirements for a certain number that a user requiers to enter(pNumber). pNumber should consist of 2 letters then 6 letters or numbers and finally a number.

I have implemented a method i found here on stackoverflow, but when i enter a number like: "LL^&%JJk9" it still gives me a positive result? to my understanding .matches checks that a string only consists of the given values?

String First = pNumber.substring(0, 2);
String Middle = pNumber.substring(2, 8);
String Last = pNumber.substring(8, 9);

if (First.matches(".*[a-zA-Z].*") && Middle.matches(".*[a-zA-Z0-9].*") && Last.matches(".*[0-9].*")) {
  greenOk.setVisibility(View.VISIBLE);
  nextBtn.setEnabled(true);
} else {
  redCross.setVisibility(View.VISIBLE);
}
thanksd
  • 54,176
  • 22
  • 157
  • 150
bananana
  • 105
  • 3
  • 10
  • 1
    This should suffice: it is the inverse of your question: http://stackoverflow.com/a/8248352/503508 – Knossos Jan 14 '16 at 14:17
  • Incidentally, your regexes are probably not what you think they are. They are essentially matching for 1. any character in the first string. 2. any character / digit in the middle string. 3. any digit in the third string. – Knossos Jan 14 '16 at 14:24
  • [RegExr](http://regexr.com/) is great for learning and testing regex. – NonlinearFruit Jan 14 '16 at 14:30
  • what do you think `.*` means? and `[a-zA-Z]`? – njzk2 Jan 14 '16 at 14:40

4 Answers4

1

Maybe something like:

    String input1 = "TYe4r5t12";
    String input2 = "LL^&%JJk9";

    String pattern = "([a-zA-Z]{2}[a-zA-Z0-9]{6}[0-9]{1})";

    Pattern r = Pattern.compile(pattern);

    Matcher m = r.matcher(input1);

    if (m.find()) {
        System.out.println("Valid !!!");
    }else{
        System.out.println("Invalid !!!");
    }
R.Costa
  • 1,395
  • 9
  • 16
1

You could use Apache Commons Lang for that. There you have methods like isNumeric and isAlphanumeric

Or use methods like Character isDigit

Leifb
  • 370
  • 7
  • 20
0

TextUtils class has various methods and one of them is given below.

TextUtils.isDigitsOnly(string)
Faizan Haidar Khan
  • 1,099
  • 1
  • 15
  • 20
-1

This Stackoverflow details how to use Apache Commons to solve your problem.

If you are looking for a Regular Expression route of solving your issue, this will likely help you:

if(pNumber.matches("[a-zA-Z]{2}[a-zA-Z0-9]{6}[0-9]")) {
    greenOk.setVisibility(View.VISIBLE);
    nextBtn.setEnabled(true);
} else {
    redCross.setVisibility(View.VISIBLE);
}
Community
  • 1
  • 1
Knossos
  • 15,802
  • 10
  • 54
  • 91
  • The middle 6 characters are letters/numbers and the last character is a number. – NonlinearFruit Jan 14 '16 at 14:36
  • The regular expression is not correct. The requirements state: 2 letters, then 6 letters or digits and finally 1 digit. The pattern you provided matches 2 letters, 6 digits and 1 letter. – Harmlezz Jan 14 '16 at 14:37