gpt4 book ai didi

python 正则表达式 : re. findall() 不按预期进行交替

转载 作者:行者123 更新时间:2023-11-28 21:40:48 27 4
gpt4 key购买 nike

我有以下代码:

testREString = '(hello | goodbye) \s darkness \s my \s old \s friend'
testString = 'sound of silence: goodbye darkness my old friend'
exp = re.compile(testREString, re.VERBOSE)
print(exp.findall(testString))

它返回:['goodbye'] 我原以为它会返回完整的句子 - 事实上,使用它选择的 exp.search(testString)正确出句子的其余部分。那为什么没有显示完整的匹配项呢?

感谢您的宝贵时间。

最佳答案

正则表达式中的

(...) 定义捕获组。

re.findall如果您的表达式定义了捕获组,则返回捕获组的内容。

您可以将其设为非捕获组 (?:hello|goodbye) 以避免这种情况。参见 What is a non-capturing group?

关于python 正则表达式 : re. findall() 不按预期进行交替,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45241171/

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