Difference in regex between Perl and Python?

I have several email addresses, 'support@company.com'and '1234567@tickets.company.com'.

In perl, I could take a string of To:raw mail and find any of the above addresses with

/\w+@(tickets\.)?company\.com/i

In python, I just wrote the above expression as '\w+@(tickets\.)?company\.com'expecting the same result. However, support@company.comit was not found at all, and findall on the second returns a list containing only 'tickets.'. It’s so clear that '(tickets\.)?'this is a problem area, but what is the difference between the regex rules between Perl and Python that I miss?

+3
source share
4 answers

re.findall:

findall(pattern, string, flags=0)
    Return a list of all non-overlapping matches in the string.

    If one or more groups are present in the pattern, return a
    list of groups; this will be a list of tuples if the pattern
    has more than one group.

    Empty matches are included in the result.

(tickets\.) - , findall . , / , ..

r'(\w+@(tickets\.)?company\.com)'
r'\w+@(?:tickets\.)?company\.com'

, , findall .

+7

, . Python:

'(\w+@(?:tickets\.)?company\.com)'
+4

:

  • , "\"
  • "."

, :

r'\w+@(tickets\.)?company\.com'

:

>>> import re
>>> exp = re.compile(r'\w+@(tickets\.)?company\.com')
>>> bool(exp.match("s@company.com"))
True
>>> bool(exp.match("1234567@tickets.company.com"))
True
+2

There is no difference in regular expressions, but there is a difference in what you are looking for. Your regular expression captures only "tickets."if it exists in both regular expressions. You probably want something like this

#!/usr/bin/python

import re

regex = re.compile("(\w+@(?:tickets\.)?company\.com)");

a = [
    "foo@company.com", 
    "foo@tickets.company.com", 
    "foo@ticketsacompany.com",
    "foo@compant.org"
];

for string in a:
    print regex.findall(string)
+1
source

Source: https://habr.com/ru/post/1706547/


All Articles