English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Any word containing 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, if 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 call mentioned above using 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("Ingrese una cadena de entrada: "); 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"); } } }
Resultado de salida
Ingrese una cadena de entrada: abc123* Given string is not alphanumeric
You can also usejava.util.regexThe package class and method (API) compile regular expressions and match them with a specific string. The following program is written using these APIs and 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("Ingrese una cadena de entrada: "); String input = sc.nextLine(); String regex = "^[a-zA-Z0-9]+$"; String data[] = input.split(" "); //Crear un objeto de patrón Pattern pattern = Pattern.compile(regex); for (String ele : data) { //Crear un objeto de coincidencia Matcher matcher = pattern.matcher(ele); if(matcher.matches()) { System.out.println("La palabra "+ele+: es alfanumérica"); } else { System.out.println("La palabra "+ele+: no es alfanumérica"); } } } }
Resultado de salida
Ingrese una cadena de entrada: hello* this$ es texto de ejemplo La palabra hello*: no es alfanumérica La palabra this$: no es alfanumérica La palabra is: es alfanumérica La palabra sample: es alfanumérica La palabra text: es alfanumérica