Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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<names.length;i++){
System.out.println("Enter your name: ");
names[i] = sc.nextLine();
}
//Regular expression to accept English alphabet
String regex = "^[a-zA-Z]*$";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
for (String name : names) {
//Creating a Matcher object
Matcher matcher = pattern.matcher(name);
if(matcher.matches()) {
System.out.println(name+" is a valid name");
} else {
System.out.println(name+" is not a valid name");
}
}
}
}
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