我有几个电子邮件地址,'support@company.com'
和 '1234567@tickets.company.com'
。
在 perl 中,我可以使用原始电子邮件的 To:
行找到上述任一地址
/\w+@(tickets\.)?company\.com/i
在 python 中,我只是将上面的正则表达式写为 '\w+@(tickets\.)?company\.com'
期望得到相同的结果。但是,根本找不到 support@company.com
,第二个 findall 返回一个仅包含 'tickets.'
的列表。很明显 '(tickets\.)?'
是问题所在,但是我遗漏的 Perl 和 Python 之间的正则表达式规则到底有什么区别?
最佳答案
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
返回的每个元组中挑选出第一个元素。
关于python - Perl 和 Python 之间正则表达式行为的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/757476/