带有 wiki 文本的 Python 正则表达式 [英] Python regular expression with wiki text

查看:19
本文介绍了带有 wiki 文本的 Python 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 正则表达式替换将 wikitext 更改为普通文本.维基链接有两种格式规则.

I'm trying to change wikitext into normal text using Python regular expressions substitution. There are two formatting rules regarding wiki link.

  • [[页面名称]]
  • [[页面名称 |要显示的文本]]

  • [[Name of page]]
  • [[Name of page | Text to display]]

(http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet)

(http://en.wikipedia.org/wiki/Wikipedia:Cheatsheet)

这里有一些让我头疼的文字.

Here is some text that gives me a headache.

CD 几乎完全由 [[披头士乐队]] 歌曲的 [[翻唱版]] 组成,这些歌曲由乔治·马丁 [[唱片制作人|制作]] 原创.

The CD is composed almost entirely of [[cover version]]s of [[The Beatles]] songs which George Martin [[record producer|produced]] originally.

上面的文字应改为:

这张 CD 几乎完全由乔治·马丁最初制作的披头士乐队歌曲的翻唱版本组成.

The CD is composed almost entirely of cover versions of The Beatles songs which George Martin produced originally.

[[ ]] 和 [[ | 之间的冲突]] 语法是我的主要问题.我不需要一个复杂的正则表达式.按顺序应用多个(可能是两个)正则表达式替换是可以的.

The conflict between [[ ]] and [[ | ]] grammar is my main problem. I don't need one complex regular expression. Applying multiple (maybe two) regular expression substitution(s) in sequence is ok.

请赐教这个问题.

推荐答案

wikilink_rx = re.compile(r'\[\[(?:[^|\]]*\|)?([^\]]+)\]\]')
return wikilink_rx.sub(r'\1', the_string)

示例:http://ideone.com/7oxuz

注意:您还可以在 http://www.mediawiki.org/wiki/中找到一些 MediaWiki 解析器Alternative_parsers.

这篇关于带有 wiki 文本的 Python 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆