4

I'm trying to check if a string is alphanumeric or not. I tried many things given in other posts but to no avail. I tried StringUtils.isAlphanumeric(), a library from Apache Commons but failed. I tried regex also from this link but that too didn't worked. Is there a method to check if a string is alphanumeric and returns true or false according to it?

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String text = fullnameet.getText().toString();
                String numRegex   = ".*[0-9].*";
                String alphaRegex = ".*[A-Z].*";

                if (text.matches(numRegex) && text.matches(alphaRegex)) {
                    System.out.println("Its Alphanumeric");
                }else{
                    System.out.println("Its NOT Alphanumeric");
                }
            }
        });
Maddy
  • 4,525
  • 4
  • 33
  • 53
Somnath Pal
  • 137
  • 1
  • 4
  • 10
  • 2
    Possible duplicate of [How to determine if a String has non-alphanumeric characters?](http://stackoverflow.com/questions/8248277/how-to-determine-if-a-string-has-non-alphanumeric-characters) – Tim May 15 '17 at 10:44
  • Possible duplicate of [java regex match for alphanumeric string](http://stackoverflow.com/questions/37070161/java-regex-match-for-alphanumeric-string) ... there are so many SO questions about this, have you tried spending 5 minutes searching? – Tim Biegeleisen May 15 '17 at 10:44
  • Yes, I've already mentioned I've searched many SO posts but not any one is working for me. – Somnath Pal May 15 '17 at 10:48
  • If you write an extension method for strings, the check can be built in. You could also use one that's already written such as the [Extensions.cs](https://www.nuget.org/packages/Extensions.cs) NuGet package that makes it as simple as: For example: "abcXYZ".IsAlphabetic() will return True whereas "abc123".IsAlphabetic() will return False. – Cornelius J. van Dyk Jan 20 '21 at 13:53

5 Answers5

13

If you want to ascertain that your string is both alphanumeric and contains both numbers and letters, then you can use the following logic:

.*[A-Za-z].*   check for the presence of at least one letter
.*[0-9].*      check for the presence of at least one number
[A-Za-z0-9]*   check that only numbers and letters compose this string

String text = fullnameet.getText().toString();
if (text.matches(".*[A-Za-z].*") && text.matches(".*[0-9].*") && text.matches("[A-Za-z0-9]*")) {
    System.out.println("Its Alphanumeric");
} else {
    System.out.println("Its NOT Alphanumeric");
}

Note that we could handle this with a single regex but it would likely be verbose and possibly harder to maintain than the above answer.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

Original from here

String myString = "qwerty123456"; System.out.println(myString.matches("[A-Za-z0-9]+"));

String myString = "qwerty123456";

if(myString.matches("[A-Za-z0-9]+"))
{
    System.out.println("Alphanumeric");
}
if(myString.matches("[A-Za-z]+"))
{
    System.out.println("Alphabet");

}

Community
  • 1
  • 1
vbijoor
  • 95
  • 1
  • 5
1

try this

 btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Pattern p = Pattern.compile("[^a-zA-Z0-9]");
            boolean hasSpecialChar = p.matcher(edittext.getText().toString()).find();

            if (!edittext.getText().toString().trim().equals("")) {
                if (hasSpecialChar) {
                    Toast.makeText(MainActivity.this, "not Alphanumeric", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Its Alphanumeric", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(MainActivity.this, "Empty value of edit text", Toast.LENGTH_SHORT).show();
            }

        }
    });
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
0

This is the code to check if the string is alphanumeric or not. For more details check Fastest way to check a string is alphanumeric in Java

public class QuickTest extends TestCase {

    private final int reps = 1000000;



    public void testRegexp() {
        for(int i = 0; i < reps; i++)
            ("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
    }



    public void testIsAlphanumeric2() {
        for(int i = 0; i < reps; i++)
            isAlphanumeric2("ab4r3rgf"+i);
    }



    public boolean isAlphanumeric2(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
                return false;
        }
        return true;
    }

}
Community
  • 1
  • 1
0

While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:

  1. Add the https://www.nuget.org/packages/Extensions.cs package to your project.
  2. Add "using Extensions;" to the top of your code.
  3. "smith23@".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
  4. Every other check in the rest of the code is simply MyString.IsAlphaNumeric().

Your example code would become as simple as:

using Extensions;

btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String text = fullnameet.getText().toString();
            //String numRegex   = ".*[0-9].*";
            //String alphaRegex = ".*[A-Z].*";

            //if (text.matches(numRegex) && text.matches(alphaRegex)) {
            if (text.IsAlphaNumeric()) {
                System.out.println("Its Alphanumeric");
            }else{
                System.out.println("Its NOT Alphanumeric");
            }
        }
    });