我正在尝试转换一些包含特定降价约定链接的文档(Wikipedia文章)。我想使这些没有链接的读者友好。公约是:
[[Article Name|Display Name]]
的双括号中的名称:
Display Name
。你知道吗[[Article Name]]
的双括号中的名称应该是
捕获时没有括号:Article Name
。你知道吗我知道我可以在嵌套的re.sub()
表达式中处理#1和#2。例如,这就是我想要的:
s = 'including the [[Royal Danish Academy of Sciences and Letters|Danish Academy of Sciences]], [[Norwegian Academy of Science and Letters|Norwegian Academy of Sciences]], [[Russian Academy of Sciences]], and [[National Academy of Sciences|US National Academy of Sciences]].'
re.sub('\[\[(.*?\|)(.*?)\]\]','\\2', # case 1
re.sub('\[\[([^|]+)\]\]','\\1',s) # case 2
)
# result is correct:
'including the Danish Academy of Sciences, Norwegian Academy of Sciences, Russian Academy of Sciences, and US National Academy of Sciences.'
为了提高效率和我自己的进步,我想知道是否有单程的方法。你知道吗
我尝试过的:在可选的组1中,我想贪婪地捕获[[
和|
(如果存在)之间的所有内容。然后在第2组中,我想捕获到]]
的所有其他内容。我只想返回第二组。你知道吗
我的问题是让贪婪的捕获成为可选:
re.sub('\[\[([^|]*\|)?(.*?)\]\]','\\2',s)
# does NOT return the desired result:
'including the Danish Academy of Sciences, Norwegian Academy of Sciences, US National Academy of Sciences.'
# is missing: 'Russian Academy of Sciences, and '
See regex in use here
\[{2}
匹配[[
(?:(?:(?!]{2})[^|])+\|)*
匹配下列任意次数(?:(?!]{2})[^|])+
Tempered greedy token匹配任何字符一次或多次,但|
或匹配]]
的位置除外\|
匹配|
字面意思((?:(?!]{2})[^|])+)
将以下内容捕获到捕获组1中(?:(?!]{2})[^|])+
Tempered greedy token匹配任何字符一次或多次,但|
或匹配]]
的位置除外]{2}
匹配]]
替换
\1
结果:
另一个对你有用的选择是。它没有上面的正则表达式那么具体,但是不包括任何lookaround。你知道吗
相关问题 更多 >
编程相关推荐