Pattern Syntax Checker Java Solution


Problem Overview

Original Problem: Pattern Syntax Checker | Hackerrank

Difficulty: Easy

Category: Regex / Pattern Matching

Description: We are given several regular expression patterns as input. Our task is to determine whether each pattern has valid syntax.

Understanding the Problem

We are not asked to evaluate whether the pattern matches any text. Instead, we’re simply checking if the pattern can be compiled by Java’s regex engine. A pattern is valid if Pattern.compile() can successfully compile it. If it throws a PatternSyntaxException, the pattern is considered invalid.

Input:

Multiple lines of input

  • The number of test cases

  • One regular expression string per test case

Output:

For each test case, print Valid if the pattern is syntactically correct, otherwise print Invalid.

Initial Reasoning

The original problem gives us template code to read in each test case. Since we're only checking the compilability of the pattern, we can wrap the Pattern.compile() call in a try-catch block. If compilation throws an exception, we print "Invalid"; otherwise, we print "Valid".

Pseudocode

// Main method:
Read the number of test cases
For each test case:
    Read the regex pattern
    Try to compile it using Pattern.compile()
        If no exception is thrown:
            Print "Valid"
        If PatternSyntaxException is caught:
            Print "Invalid"

Solution Code

// Note this is one of many possible solutions
import java.util.Scanner;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int testCases = Integer.parseInt(scanner.nextLine());

        while(testCases > 0){
            String pattern = in.nextLine();

            try {
                // Attempt to compile the regex pattern
                Pattern.compile(pattern);
                System.out.println("Valid");
            } catch (PatternSyntaxException e) {
                // If compilation fails, it's an invalid pattern
                System.out.println("Invalid");
            }

            testCases--;
        }

        scanner.close(); 
    }
}
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Renamed variables:

    Using more descriptive names improves the clarity of the code and makes it easier for anyone reading the code to understand what each variable represents.