用于查找MediaWiki标记链接内容的Python正则表达式

unm*_*ted 3 python regex mediawiki

如果我有一些xml包含以下mediawiki标记:

"...收集于12世纪,其中[[亚历山大大帝]]是英雄,并且代表他,有点像英国[[亚瑟王|亚瑟]]"

什么是适当的论据,如:

re.findall([[__?__]], article_entry)

我有点躲过双方括号,并得到文本的正确链接,如: [[Alexander of Paris|poet named Alexander]]

Unk*_*own 5

这是一个例子

import re

pattern = re.compile(r"\[\[([\w \|]+)\]\]")
text = "blah blah [[Alexander of Paris|poet named Alexander]] bldfkas"
results = pattern.findall(text)

output = []
for link in results:
    output.append(link.split("|")[0])

# outputs ['Alexander of Paris']
Run Code Online (Sandbox Code Playgroud)

版本2,更多地放入正则表达式,但结果,更改输出:

import re

pattern = re.compile(r"\[\[([\w ]+)(\|[\w ]+)?\]\]")
text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]"
results = pattern.findall(text)

# outputs [('a', '|b'), ('c', '|d'), ('efg', '')]

print [link[0] for link in results]

# outputs ['a', 'c', 'efg']
Run Code Online (Sandbox Code Playgroud)

版本3,如果您只想要没有标题的链接.

pattern = re.compile(r"\[\[([\w ]+)(?:\|[\w ]+)?\]\]")
text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]"
results = pattern.findall(text)

# outputs ['a', 'c', 'efg']
Run Code Online (Sandbox Code Playgroud)