%他在正则表达式中表现出奇怪的行为

2024-03-29 09:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想在括号前最多捕获5个单词。我有一个在括号里的缩写列表。所以我使用以下代码-

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会导致regex匹配有很大的不同(在它周围有不必要的括号,重复首字母缩写词等等)

如何正确使用第一个regex,以便使用循环自动执行过程,而不必每次都在regex中输入精确的字符串?你知道吗


Tags: the字符串inreworlddsfind括号
1条回答
网友
1楼 · 发布于 2024-03-29 09:39:32

您需要确保传递的变量被正确转义,以便在regex模式中用作文本。使用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如果模式中没有定义捕获组,则将返回匹配值。你知道吗

还建议在定义regex模式时使用原始字符串文本,以避免出现不明确的情况。你知道吗

相关问题 更多 >