wikitext temp上的Python regex

2024-04-25 07:56:45 发布

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

我正在尝试用Python从表单的wikitext模板中删除换行符:

{{cite web
|title=Testing
|url=Testing
|editor=Testing
}}

应通过以下方法获得回复sub地址:

{{cite web|title=Testing|url=Testing|editor=Testing}}

我已经用Python正则表达式试了几个小时了,但是还没有成功。例如,我试过:

while(re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}')):
     textmodif=re.sub(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', r'{cite web\1\3}}', textmodif,re.DOTALL)

但是它并没有像预期的那样工作(即使没有while循环,它也不能在第一次换行时工作)。你知道吗

我发现了一个类似的问题,但没用:Regex for MediaWiki wikitext templates。我对Python很陌生,所以请不要对我太苛刻:-)

先谢谢你。你知道吗


Tags: 方法re模板weburl表单title地址
1条回答
网友
1楼 · 发布于 2024-04-25 07:56:45

您需要为.打开换行符匹配;它不匹配换行符,否则:

re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', inputtext, flags=re.DOTALL)

要匹配的文本中有多个换行符,因此仅匹配一组连续的换行符是不够的。你知道吗

^{} documentation

Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.

您可以使用一个re.sub()调用一次性删除cite节中的所有换行,而不使用循环:

re.sub(r'\{cite web.*?[\r\n]+.*?\}\}', lambda m: re.sub('\s*[\r\n]\s*', '', m.group(0)), inputtext, flags=re.DOTALL)

这使用一个嵌套的正则表达式从匹配的文本中删除所有包含至少一个换行符的空白。你知道吗

演示:

>>> import re
>>> inputtext = '''\
... {{cite web
... |title=Testing
... |url=Testing
... |editor=Testing
... }}
... '''
>>> re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', inputtext, flags=re.DOTALL)
<_sre.SRE_Match object at 0x10f335458>
>>> re.sub(r'\{cite web.*?[\r\n]+.*?\}\}', lambda m: re.sub('\s*[\r\n]\s*', '', m.group(0)), inputtext, flags=re.DOTALL)
'{{cite web|title=Testing|url=Testing|editor=Testing}}\n'

相关问题 更多 >