python - 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']
解决方案
你有多余的括号,导致两组。修复它有效:
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']
推荐阅读
- php - php在测试之间重置静态方法范围变量
- reactive-programming - 如何链接来自不同服务的响应,以便在 WebFlux 中使用“那些响应”创建 Flux 响应?
- linux - 嵌入式参数替换
- reactjs - React ProtectedRoutes 用于渲染功能组件
- javascript - 点击事件后如何获得退货并保存 - Javascript?
- c# - 如何在 winforms 控件中创建具有类型列表的自定义 TypeConverter?
- automapper - 如何将源成员的属性自动映射到目标属性?
- atom-editor - 如何让 Atom linter 包工作?
- vba - 编写 VBA 脚本以在 AS400 上启动录制的宏的最佳方法是什么?
- vue.js - 单击时打开 Vue 图像模式