Java Program to perform pattern based text matching.
Objective
Write a Java program to validate text (like a Name) using Regular Expressions (Regex).
Algorithm / Approach
- Prompt the user for a Name.
- Define a regex pattern:
"[A-Za-z ]+". - Use the String method
matches(pattern). - If it returns true, accept the detail; otherwise, reject it.
Test.java
import java.util.*;
class Test {
public static void main(String [] ar)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = sc.nextLine();
//To check alphabet & space
String pattern = "[A-Za-z ]+";
if(name.matches(pattern)){
System.out.println("DETAIL ACCEPTED");
}
else{
System.out.println("INVALID NAME");
System.out.print("Only chars allowed");
}
}
}
Expected Output
//execution 1 Enter Name: Ayaan Khan DETAIL ACCEPTED //execution 2 Enter Name: Ajay1 INVALID NAME Only chars allowed!!
Explanation of the Program
- Regular Expressions (Regex) are powerful search patterns used for string validation.
- The pattern
[A-Za-z ]+means: Match any character from uppercase A-Z, lowercase a-z, or a space character. The+symbol means "one or more times". - If the user types a number (like "Ajay1"), the
matches()function immediately returns false.
Complexity
Time Complexity
O(n) - Where n is the length of the string.
Space Complexity
O(1)