In this Java program, the user is asked to input a number of test cases, followed by that many strings. Each string is supposed to represent a regular expression pattern. The task is to check whether each string is a valid regular expression pattern or not.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach is straightforward. For each test case, the program reads a string and tries to compile it into a Pattern object using the Pattern.compile() method. If the string is a valid regular expression, the method will succeed and the program will print 'Valid'. If the string is not a valid regular expression, the method will throw an exception, which the program catches and then prints 'Invalid'.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.strings;
import java.util.Scanner;
import java.util.regex.Pattern;
/**
*
*/
public class PatternSyntaxChecker {
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.compile(pattern);
System.out.println("Valid");
} catch (Exception e) {
System.out.println("Invalid");
}
}
in.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.