Check if a string is alphanumeric

Viewed 14092

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

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