Incorrect Regex - Python HackerRank Solution
Hello Friends, How are you? Today I am going to solve the HackerRank Incorrect Regex Problem in Python with a very easy explanation. In this article, you will get one or more approaches to solving this problem. So let's start-
{tocify} $title={Table of Contents}
HackerRank Python Incorrect Regex Solution - Problem Statement
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 0
2 .*\+ .*+ {codeBox}
Sample Output 0
True False {codeBox}
Explanation 0
.*\+ : Valid regex.
.*+: Has the error multiple repeats. Hence, it is invalid.
Python Incorrect Regex - Hacker Rank Solution
Approach I: Incorrect Regex HackerRank Python Solution in Pypy 3
# ========================
# Information
# ========================
# Name: Incorrect Regex in Python HackerRank
# Direct Link: https://www.hackerrank.com/challenges/incorrect-regex/problem
# Difficulty: Easy
# Max Score: 20
# Language: Pypy 3
# ========================
# Solution Start
# ========================
#Incorrect Regex in Python - Hacker Rank Solution
# 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')
#Incorrect Regex in Python - Hacker Rank Solution END
# MyEduWaves
2nd Approach: Incorrect Regex HackerRank Python Solution in Python 3
# ========================
# Information
# ========================
# Name: Incorrect Regex in Python HackerRank
# Direct Link: https://www.hackerrank.com/challenges/incorrect-regex/problem
# Difficulty: Easy
# Max Score: 20
# Language: Python 3
# ========================
# Solution Start
# ========================
#Incorrect Regex in Python - Hacker Rank Solution
# Enter your code here. Read input from STDIN. Print output to STDOUT
import re
for _ in range(int(input())):
ans = True
try:
reg = re.compile(input())
except re.error:
ans = False
print(ans)
#Incorrect Regex in Python - Hacker Rank Solution END
# MyEduWaves
Disclaimer: The above Problem ( Python Incorrect Regex ) is generated by Hackerrank but the Solution is Provided by MyEduWaves. This tutorial is only for Educational and Learning purposes. Authority if any queries regarding this post or website fill out the contact form.
I hope you have understood the solution to this HackerRank Problem. All these three solutions will pass all the test cases. Now visit Python Incorrect Regex Hackerrank Problem and try to solve it again.
All the Best!
Tags:
HackerRank Python