HackerRank Python Solution - Errors and Exception - Incorrect Regex

  • 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 contain 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 repeats. Hence, it is invalid.
Solution:

import re

T = int(input())

for _ in range(T):
    output = True
    try:
        re.compile(input())
    except re.error:
        output = False
    print(output)
Disclaimer: The problem statement is given by hackerrank.com but the solution is generated by the Geek4Tutorial admin. If there is any concern regarding this post or website, please contact us using the contact form. Thank you!

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...