Header Ad

HackerRank Pattern Syntax Checker solution in java

In this HackerRank Pattern syntax Checker problem in the java programming language, 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.

HackerRank Pattern Syntax Checker solution in java


HackerRank Pattern Syntax Checker problem solution in java programming.

import java.util.Scanner;
import java.util.regex.*;

public class Solution
{
   public static void main(String[] args){
      Scanner in = new Scanner(System.in);
      int testCases = Integer.parseInt(in.nextLine());
      while(testCases>0){
         String pattern = in.nextLine();
          try{
              Pattern p = Pattern.compile(pattern);
              System.out.println("Valid");
          }catch(Throwable t){
              System.out.println("Invalid");
          }
          testCases--;
             //Write your code
      }
   }
}



A solution in java8 programming.

import java.util.Scanner;
import java.util.regex.*;

public class Solution
{
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		int testCases = Integer.parseInt(in.nextLine());
		while(testCases>0){
			String pattern = in.nextLine();
          	//Write your code
              try {
                Pattern.compile(pattern);
                System.out.println("Valid");
            } catch (PatternSyntaxException e) {
                System.out.println("Invalid");
            }
            testCases--;
		}
	}
}

Post a Comment

0 Comments