OneBite.Dev - Coding blog in a bite size

check if a string contains only alphanumeric characters in java

Code snippet on how to check if a string contains only alphanumeric characters in java

  String testString = "abc123"; 
  Boolean result = testString.matches("[a-zA-Z0-9]+");
  if (result) {
    System.out.println("The string contains only alphanumeric characters");
  }

This code checks if a given string contains only alphanumeric characters. First, a string variable “testString” is declared and initialized with a value “abc123”. Second, a Boolean variable “result” is created and the method “.matches” is used on “testString” with a regular expression “[a-zA-Z0-9]+” as an argument. The expression is used to check whether only alphanumeric characters are present in the string. Third, an if statement is used to check if the value of the variable “result” is true. If true, it prints “The string contains only alphanumeric characters”.

java