gpt4 book ai didi

python - %s 在正则表达式中表现出奇怪的行为

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:14 25 4
gpt4 key购买 nike

我有一个字符串,我想在其中查找括号前面的一些单词。假设字符串是 -

'there are many people in the world having colorectal cancer (crc) who also have the depression syndrome (ds)'

我想在括号前捕获最多 5 个单词。我有一个括号内的缩写列表 acronym_list - [(crc), (ds)]。所以我使用以下代码 -

acrolen=5
rt=[]
for acro in acronym_list:
find_words= re.findall('((?:\w+\W+){1,%d}%s)' %(acrolen, acro), text, re.I)
for word in find_words:
rt.append(word)
print rt

但这给出了这个结果 -

('the world having colorectal cancer (crc', 'crc')
('also have the depression syndrome (ds', 'ds')

如果我使用正则表达式 -

find_words= re.findall('((?:\w+\W+){1,%d}\(crc\))' %(acrolen),s, re.I)

然后它就能准确找到我想要的东西,即 -

the world having colorectal cancer (crc)

问题是 - 为什么在这里使用 %s 表示字符串会导致正则表达式匹配差异如此之大(周围有不必要的括号,重复缩写词等......)

如何正确使用第一个正则表达式,以便可以使用循环自动执行该过程,而不必每次都在正则表达式中输入确切的字符串?

最佳答案

您需要确保传递的变量正确转义,以便用作正则表达式模式内的文字文本。使用re.escape(acro):

import re
text = "there are many people in the world having colorectal cancer (crc) who also have the depression syndrome (ds)"
acrolen=5
rt=[]
acronym_list = ["(crc)", "(ds)"]
for acro in acronym_list:
p = r'((?:\w+\W+){1,%d}%s)' %(acrolen, re.escape(acro))
# Or, use format:
# p = r'((?:\w+\W+){{1,{0}}}{1})'.format(acrolen, re.escape(acro))
find_words= re.findall(p, text, re.I)
for word in find_words:
rt.append(word)
print rt

请参阅Python demo

另外,请注意,您不需要用捕获组将整个模式括起来,如果模式中未定义捕获组,re.findall 将返回匹配值。

还建议在定义正则表达式模式时使用原始字符串文字,以避免出现歧义的情况。

关于python - %s 在正则表达式中表现出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40109204/

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