Program to find whether a string is alphanumeric.


Any word that contains numbers and letters is known as alphanumeric. The following regular expression matches the combination of numbers and letters.

"^[a-zA-Z0-9]+$";

The matches method of the String class accepts a regular expression (in the form of a String) and matches it with the current string in case the match this method returns true else it returns false.

Therefore, to find whether a particular string contains alpha-numeric values −

  • Get the string.
  • Invoke the match method on it bypassing the above mentioned regular expression.
  • Retrieve the result.

Example 1

import java.util.Scanner;
public class AlphanumericString {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.next();
      String regex = "^[a-zA-Z0-9]+$";
      boolean result = input.matches(regex);
      if(result) {
         System.out.println("Given string is alpha numeric");
      } else {
         System.out.println("Given string is not alpha numeric");
      }
   }
}

Output

Enter input string:
abc123*
Given string is not alpha numeric

Example 2

You can also compile a regular expression and match it with a particular string using the classes and methods (APIs) of the java.util.regex package. The following program is written using these APIs and it verifies whether a given string is alpha-numeric.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      String regex = "^[a-zA-Z0-9]+$";
      String data[] = input.split(" ");
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      for (String ele : data){
         //creating a matcher object
         Matcher matcher = pattern.matcher(ele);
         if(matcher.matches()) {
            System.out.println("The word "+ele+": is alpha numeric");
         } else {
            System.out.println("The word "+ele+": is not alpha numeric");
         }
      }
   }
}

Output

Enter input string:
hello* this$ is sample text
The word hello*: is not alpha numeric
The word this$: is not alpha numeric
The word is: is alpha numeric
The word sample: is alpha numeric
The word text: is alpha numeric

Updated on: 21-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements