English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Any word containing both numbers and letters is called alphanumeric. The following regular expression matches combinations of numbers and letters.
"^[a-zA-Z0-9]+$";
The match method of the String class accepts a regular expression (in the form of String) and matches it with the current string, in case the match method returns true, it returns false.
Therefore, to find out whether a specific string contains alphanumeric values-
Get the string.
Bypass the match method mentioned above by calling the regular expression.
Retrieve the result.
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 alphanumeric"); } else { System.out.println("Given string is not alphanumeric"); } } }
Output Result
Enter input string: abc123* Given string is not alphanumeric
You can also usejava.util.regexThe class and method (API) of the package compile regular expressions and match them with a specific string. The following program is written using these APIs and it verifies whether the given string is alphanumeric.
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(" "); //Create a pattern object Pattern pattern = Pattern.compile(regex); for (String ele : data) { //Create a match 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 Result
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