如何设计一个正则表达式来捕获两个字符串之间的所有字符? 具体来说,从这个大字符串:
研究表明...[^title=食用鱼和中风的发生率:队列研究的荟萃分析]...另一项实验表明...[^title=第二个标题]
我想提取[^title=
和]
之间的所有字符,即Fish consumption and incidence of stroke: a meta-analysis of队列研究
和第二题
。
我想我将不得不使用 re.findall(),我可以从这个开始:re.findall(r'\[([^]]*)\]', big_string)
,这将给我方括号 [ ]
之间的所有匹配项,但我不确定如何扩展它。
最佳答案
>>> text = "Studies have shown that...[^title=Fish consumption and incidence of stroke: a meta-analysis of cohort studies]... Another experiment demonstrated that... [^title=The second title]"
>>> re.findall(r"\[\^title=(.*?)\]", text)
['Fish consumption and incidence of stroke: a meta-analysis of cohort studies', 'The second title']
这是正则表达式的分割:
\[
是转义的 [ 字符。
\^
是转义的 ^ 字符。
title=
匹配 title=
(.*?)
非贪婪地匹配任何字符,并将它们放在一个组中(以便 findall 提取)。这意味着它会在找到...时停止。
\]
,这是一个转义的 ] 字符。
关于python - 正则表达式返回两个字符串之间的所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21901491/