python - 如何在正则表达式中为一组条件定义量词?
问题描述
我有这个字符串:
"Za @Foo_Bar: @BAR_foo @FooBAR @BArfoo"
和这样的正则表达式模式:
((Za\s)?@[A-Za-z0-9_]*)|(@[A-Za-z0-9_]*)
或者
(Za\s)?@[A-Za-z0-9_]*
我希望它返回此列表:
['Za @Foo_Bar','BAR_foo','FooBAR','BArfoo']
但我得到了意想不到的结果:
>>> import re
>>> import regex
>>> a = "Za @Foo_Bar: @BAR_foo @FooBAR @BArfoo"
>>> regex.fullmatch(u'((Za\s)?@[A-Za-z0-9_]*)|(@[A-Za-z0-9_]*)',a) is None
True
>>> re.findall(u'((Za\s)?@[A-Za-z0-9_]*)|(@[A-Za-z0-9_]*)',a)
[('Za @Foo_Bar', 'Za ', ''), ('@BAR_foo', '', ''), ('@FooBAR', '', ''), ('@BArfoo', '', '')]
第二个结果更有说服力,但它包含很多垃圾值:
>>> regex.findall(u'((Za\s)?@[A-Za-z0-9_]*)|(@[A-Za-z0-9_]*)',a)
[('Za @Foo_Bar', 'Za ', ''), ('@BAR_foo', '', ''), ('@FooBAR', '', ''), ('@BArfoo', '', '')]
>>> match = re.search(u'((Za\s)?@[A-Za-z0-9_]*)|(@[A-Za-z0-9_]*)',a)
>>> match.groups()
('Za @Foo_Bar', 'Za ', None)
为什么fullmatch
返回None
?我怎样才能得到一个干净的清单?
解决方案
不要使用组:
import re
s = "Za @Foo_Bar: @BAR_foo @FooBAR @BArfoo"
g = re.findall(r'(?:Za\s)@\w+|(?<=@)\w+', s)
print(g)
输出:
['Za @Foo_Bar', 'BAR_foo', 'FooBAR', 'BArfoo']
解释:
(?:Za\s) # non capture group
@ # @
\w+ # 1 or more word character
| #
(?<=@) # lookbehind, make sure we have @ before
\w+ # 1 or more word character
推荐阅读
- python - Iterate in dictionary for value that matches the first 5 numbers in a filename
- python - 将 txt 文件拆分为较小的文件,但保留标题
- laravel - 如何访问从控制器传递到辅助函数中查看的变量?
- html - 如何使文本和图标水平对齐在屏幕调整大小时保持一致?
- android - GCM 获取用于从服务器发送通知的令牌
- python - 如何生成随机 rgb 颜色列表
- python-3.x - 在 ubuntu 18.04 上安装软件包时出现 pip3 错误 - 命令“python setup.py egg_info”失败,错误代码为 1”
- c# - 找出扩展方法的来源
- python - 如何强制 pip 安装最新版本的 django?
- nginx - Nginx 服务器返回奇怪的字符