简体   繁体   中英

how to check if string contains only numerics or letters properly? Android

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);
}

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 !!!");
    }

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

Or use methods like Character isDigit

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

TextUtils.isDigitsOnly(string)

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM