Issue in finding email id from a string - Python

Viewed 37

Can somebody help me figure out what is the issue with the below code:

import re

class RegexTest(object):
    
    def regex_test(self, reg, string):
        reg_pattern = repr(reg)[1:-1]
        match = re.search(reg_pattern, string)
        if (match is not None):
            return match.group(0)
        else:
            return None
        
test = RegexTest()
print(test.regex_test('[A-Za-z0-9\._]+\@\w+\.\w{2,4}', 'My email id is: abcd123_hello@yahoo.com'))

Output:

None

Any help would be highly appreciated.

1 Answers

If you print the regex pattern you create inside regex_test method, you will see you are not using the literal string pattern itself, but a string literal converted to literal text. That means, all backslashes become doubled in the pattern, and a \\ in a regex pattern matches a literal \ char.

Look:

print(repr(reg)[1:-1])
# => [A-Za-z0-9\\._]+\\@\\w+\\.\\w{2,4}
print(reg)
# => [A-Za-z0-9\._]+\@\w+\.\w{2,4}

Use

def regex_test(self, reg, string):
    match = re.search(reg, string)
    if match is not None:
        return match.group(0)
    else:
        return None

You do not need to wrap the if condition with parentheses.

When defining a pattern, it is recommended to use a raw string literal and you do not need to escape . inside a character class and a @ char:

print(test.regex_test(r'[A-Za-z0-9._]+@\w+\.\w{2,4}', 'My email id is: abcd123_hello@yahoo.com'))
Related