regex捕获括号中的文本,省略可选前缀

2024-04-20 13:06:26 发布

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

我正在尝试转换一些包含特定降价约定链接的文档(Wikipedia文章)。我想使这些没有链接的读者友好。公约是:

  1. 应忽略管道和前面的文本以及括起来的括号,捕获模式为[[Article Name|Display Name]]的双括号中的名称: Display Name。你知道吗
  2. 模式[[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 '

Tags: andofthe方法namerearticle括号
1条回答
网友
1楼 · 发布于 2024-04-20 13:06:26

See regex in use here

\[{2}(?:(?:(?!]{2})[^|])+\|)*((?:(?!]{2})[^|])+)]{2}
  • \[{2}匹配[[
  • (?:(?:(?!]{2})[^|])+\|)*匹配下列任意次数
    • (?:(?!]{2})[^|])+Tempered greedy token匹配任何字符一次或多次,但|或匹配]]的位置除外
    • \|匹配|字面意思
  • ((?:(?!]{2})[^|])+)将以下内容捕获到捕获组1中
  • ]{2}匹配]]

替换\1

结果:

including the Danish Academy of Sciences, Norwegian Academy of Sciences, Russian Academy of Sciences, and US National Academy of Sciences.

另一个对你有用的选择是。它没有上面的正则表达式那么具体,但是不包括任何lookaround。你知道吗

\[{2}(?:[^]|]+\|)*([^]|]+)]{2}

相关问题 更多 >