gpt4 book ai didi

python - 在一行中获取捕获组

转载 作者:太空狗 更新时间:2023-10-29 17:54:28 26 4
gpt4 key购买 nike

有一个已知的“模式”来获取捕获的组值或如果没有匹配则为空字符串:

match = re.search('regex', 'text')
if match:
value = match.group(1)
else:
value = ""

或:

match = re.search('regex', 'text')
value = match.group(1) if match else ''

是否有一种简单的 pythonic 方法可以在一行中完成此操作?

换句话说,我可以为捕获组提供默认值以防找不到吗?


例如,我需要从 key= 字符串之后的文本中提取所有字母数字字符(和 _):

>>> import re
>>> PATTERN = re.compile('key=(\w+)')
>>> def find_text(text):
... match = PATTERN.search(text)
... return match.group(1) if match else ''
...
>>> find_text('foo=bar,key=value,beer=pub')
'value'
>>> find_text('no match here')
''

find_text() 是否有可能成为一行代码?

这只是一个例子,我正在寻找一种通用的方法。

最佳答案

引自MatchObjects docs ,

Match objects always have a boolean value of True. Since match() and search() return None when there is no match, you can test whether there was a match with a simple if statement:

match = re.search(pattern, string)
if match:
process(match)

由于没有其他选择,并且当您使用函数时,我想提出这个替代方案

def find_text(text, matches = lambda x: x.group(1) if x else ''):
return matches(PATTERN.search(text))

assert find_text('foo=bar,key=value,beer=pub') == 'value'
assert find_text('no match here') == ''

其实是一样的,只是默认参数化了你需要做的检查。

想到@Kevin 的解决方案和@devnull 在评论中的建议,你可以这样做

def find_text(text):
return next((item.group(1) for item in PATTERN.finditer(text)), "")

这利用了 next 接受默认值作为参数返回的事实。但这有在每次迭代中创建生成器表达式的开销。所以,我会坚持使用第一个版本。

关于python - 在一行中获取捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23366848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com