Kumar Sanu
Kumar Sanu

Reputation: 226

re.match is not working as I expect in python3

Link to the problem is: https://www.hackerrank.com/challenges/validating-credit-card-number/problem

Regexp is working fine in online regex tester but not working perfectly when I am using re.match() of python.
For following condition this regular expression is not working:-
It must NOT have 4 or more consecutive repeated digits.

import re
test_case=int(input())
for _ in range(test_case):
    print('Valid' if re.match("^(?!.*(\d)(-?\1){3})[456]{1}\d{3}[-]?\d{4}[-]?\d{4}[-]?\d{4}$",input()) is not None else "Invalid")

For example:- 5133-3367-8912-3456
In this case its giving "No matches" in online regex tester. But in case of python3 with re.match, it's returning match object re.Match object; span=(0, 19), match='5133-3367-8912-3456'

So for this test case of the above mentioned hackerrank problem,this is printing "Valid" in place of "Invalid".

Upvotes: 1

Views: 1192

Answers (1)

oittaa
oittaa

Reputation: 595

As @snakecharmerb said, some of the backslashes get interpreted in double quotes.

import re
a = r"^(?!.*(\d)(-?\1){3})[456]{1}\d{3}[-]?\d{4}[-]?\d{4}[-]?\d{4}$"
b = "^(?!.*(\d)(-?\1){3})[456]{1}\d{3}[-]?\d{4}[-]?\d{4}[-]?\d{4}$"
print(a)
print(b)

test_case = "5133-3367-8912-3456"
print('Valid' if re.match(a,test_case) is not None else "Invalid")
print('Valid' if re.match(b,test_case) is not None else "Invalid")

output

^(?!.*(\d)(-?\1){3})[456]{1}\d{3}[-]?\d{4}[-]?\d{4}[-]?\d{4}$
^(?!.*(\d)(-?){3})[456]{1}\d{3}[-]?\d{4}[-]?\d{4}[-]?\d{4}$
Invalid
Valid

Upvotes: 2

Related Questions