HackerRank Java- Pattern Syntax Checker
Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, we have to specify one using some well-defined syntax.
In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid.
- import java.util.Scanner;
- import java.util.regex.Pattern;
- import java.util.regex.PatternSyntaxException;
-
- public class Solution {
- public static void main(String[] args) {
- Scanner scan = new Scanner(System.in);
- int testCases = scan.nextInt();
- scan.nextLine();
- while (testCases-- > 0) {
- String pattern = scan.nextLine();
- try {
- Pattern.compile(pattern);
- System.out.println("Valid");
- } catch (PatternSyntaxException exception) {
- System.out.println("Invalid");
- }
- }
- scan.close();
- }
- }