Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to perform pattern based text matching.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Prompt the user for a Name.
  2. Define a regex pattern: "[A-Za-z ]+".
  3. Use the String method matches(pattern).
  4. 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)
ADVERTISEMENT