我有一个字符串,我想在其中找到括号前面的一些单词。假设字符串是-
'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中输入精确的字符串?你知道吗
您需要确保传递的变量被正确转义,以便在regex模式中用作文本。使用
re.escape(acro)
:参见Python demo
另外,请注意,您不需要用捕获组将整个模式括起来,
re.findall
如果模式中没有定义捕获组,则将返回匹配值。你知道吗还建议在定义regex模式时使用原始字符串文本,以避免出现不明确的情况。你知道吗
相关问题 更多 >
编程相关推荐