wikitext模板上的Python正则表达式
我正在尝试使用Python从表单的wikitext模板中删除换行符:wikitext模板上的Python正则表达式,python,regex,wikitext,Python,Regex,Wikitext,我正在尝试使用Python从表单的wikitext模板中删除换行符: {{cite web |title=Testing |url=Testing |editor=Testing }} 应通过re.sub获得以下信息: {{cite web|title=Testing|url=Testing|editor=Testing}} 我已经用Python正则表达式尝试了几个小时,但还没有成功。例如,我尝试过: while(re.search(r'\{cite web(.*?)([\r\n]+)(.*
{{cite web
|title=Testing
|url=Testing
|editor=Testing
}}
应通过re.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循环,它也不能在第一行中断时工作)
我发现了一个类似的问题,但没有帮助:。我是Python新手,所以请不要对我太苛刻:-)
提前谢谢。您需要为
打开换行符匹配;它与换行符不匹配,否则:
re.search(r'\{cite web(.*?)([\r\n]+)(.*?)\}\}', inputtext, flags=re.DOTALL)
要匹配的文本中有多个换行符,因此仅匹配一组连续换行符是不够的
从:
使“.
特殊字符完全匹配任何字符,包括换行符;如果没有此标志,。
将匹配除换行符以外的任何内容
您可以使用一个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)
这将使用嵌套正则表达式从匹配文本中删除至少包含一个换行符的所有空白
演示:
>>重新导入
>>>inputtext=''\
... {{引用网站
…|标题=测试
…| url=测试
…|编辑器=测试
... }}
... '''
>>>re.search(r'\{cite web(.*?([\r\n]+)(.*?\}}),inputtext,flags=re.DOTALL)
>>>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”
>>> 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'