首页 > 解决方案 > findall 返回整个正则表达式匹配作为其第一个索引,即使其中存在一个组

问题描述

我正在使用使用正则表达式对象的 findall 方法,但我得到了字符串的整个表达式匹配,尽管其中存在一个组。

我正在使用 python 3.7.3

import re
def emailfinder(spam):
   emailregx=re.compile(r'''(
   [a-zA-Z0-9%_+-.]+
   @
   [a-zA-Z0-9.-]+
   (\.[a-zA-Z]{2,4})
   )''',re.VERBOSE)
   return emailregx.findall(spam)
print(emailfinder('tara9090@gmail.com blah monkey tanbajg@chscv.in'))

输出是[('tara9090@gmail.com', '.com'), ('tanbajg@chscv.in', '.in')]。但我期待它是['.com','.in']

标签: pythonregexfindall

解决方案


你有多余的括号,导致两组。修复它有效:

import re
def emailfinder(spam):
   emailregx=re.compile(r'''
   [a-zA-Z0-9%_+-.]+
   @
   [a-zA-Z0-9.-]+
   (\.[a-zA-Z]{2,4}
   )''',re.VERBOSE)
   return emailregx.findall(spam)

print(emailfinder('tara9090@gmail.com blah monkey tanbajg@chscv.in'))
['.com', '.in']

推荐阅读