python - 如何从 Python 中的一组正则表达式匹配中提取第一个非空匹配?

标签 python regex

假设我有一个正则表达式(a)|(b)|(c)|(d)。如果我将它应用于文本 'foobar' 我会得到一个匹配对象

>>> compiled = re.compile('(a)|(b)|(c)|(d)')
>>> compiled.search('foobar').groups()
(None, 'b', None, None)

如何从这里提取 'b'?或者一般来说,如何从未知数量的组中提取第一个匹配项(动态构建正则表达式时可能发生)?

最佳答案

>>> g = (None, 'b', None, None)
>>> next(x for x in g if x is not None)
'b'

>>> g = (None, None, None)
>>> next((x for x in g if x is not None), "default")  # try this with filter :)
'default'

>>> g = (None, None, None)  # so you know what happens, and what you could catch
>>> next(x for x in g if x is not None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

关于python - 如何从 Python 中的一组正则表达式匹配中提取第一个非空匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2498935/

相关文章:

python - 使用python在表单中选择动态填充下拉列表

javascript - expressjs 绑定(bind)除 2 个文件夹之外的所有路由?

javascript正则表达式非捕获比根本没有括号更快

java - 奇怪的 Java 替换优先

java - String.matches 每次测试都失败?

python+docker : docker volume mounting with bad perms, 数据默默丢失

python - VS Code 无法识别 Python 虚拟环境

python - Pandas DataFrame 根据其他列过滤 str 列

python - 在 Pandas 数据帧上运行 sql 查询

python - 使用 Scrapy 从文本中删除 <u> 字符