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 Regular expression to check if a string contains alphabet
Following is the regular expression to match alphabet in the given input −
"^[a-zA-Z]*$"
Where,
- ^ matches the starting of the sentence.
- [a-zA-z] matches the lower case and upper case letters.
- * indicates the occurrence for zero or more times.
- & indicates the end of the line.
Example 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ContainsAlphabetExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String names[] = new String[5];
for(int i=0; i
Output
Enter your name:
krishna
Enter your name:
kasyap
Enter your name:
maruthi#
Enter your name:
Sai_Ram
Enter your name:
Vani.Viswanath
krishna is a valid name
kasyap is a valid name
maruthi# is not a valid name
Sai_Ram is not a valid name
Vani.Viswanath is not a valid name
Example 2
import java.util.Scanner;
public class Just {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
String regex = "^[a-zA-Z]*$";
boolean result = name.matches(regex);
if(result) {
System.out.println("Given name is valid");
} else {
System.out.println("Given name is not valid");
}
}
}
Output
Enter your name:
vasu#dev
Given name is not valid
Advertisements
