Incorrect Regex in Python | HackerRank Solution

Hello coders, today we are going to solve Incorrect Regex HackerRank Solution in Python.

Incorrect Regex

Task

You are given a string S.
Your task is to find out whether S is a valid regex or not.

Input Format

The first line contains integer T, the number of test cases.
The next T lines contains the string S.

Constraints

  • 0 < T < 100

Output Format

Print “True” or “False” for each test case without quotes.

Sample Input

2
.*\+
.*+

Sample Output

True
False

Explanation

.*\+ : Valid regex.
.*+: Has the error multiple repeat. Hence, it is invalid.

Solution – Incorrect Regex in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
T = int(input())
for _ in range(T):  
    try:
        print(bool(re.compile(input())))
    except:
        print('False')

Disclaimer: The above Problem (Incorrect Regex) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *