Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Java regex program to verify whether a String contains at least one alphanumeric character.
Following regular expression matches a string that contains at least one alphanumeric characters −
"^.*[a-zA-Z0-9]+.*$";
Where,
^.* Matches the string starting with zero or more (any) characters.
[a-zA-Z0-9]+ Matches at least one alpha-numeric character.
.*$ Matches the string ending with zero or more (ant) characters.
Example 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a string");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression
String regex = "^.*[a-zA-Z0-9]+.*$";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
if(matcher.matches()) {
System.out.println("Given string is valid");
} else {
System.out.println("Given string is not valid");
}
}
}
Output 1
Enter a string ###test123$$$ Given string is valid
Output 2
Enter a string ####$$$$ Given string is not valid
Example 2
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a string");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression
String regex = "^.*[a-zA-Z0-9]+.*$";
boolean result = input.matches(regex);
if(result) {
System.out.println("Valid match");
}else {
System.out.println("In valid match");
}
}
}
Output 1
Enter a string ###test123$$$ Valid match
Output 2
Enter a string ####$$$$ In valid match
Advertisements
