Python non-greedy regex to clean xml

烈酒焚心 提交于 2019-12-06 07:50:32

The dot does not match newlines unless you specify the re.DOTALL flag.

re.sub("</([a-zA-Z]+)>.*?<","</\\1><",text, flags=re.DOTALL)

should work fine. (If it does not, my python is at fault, not the regex. Please correct.)

I think it is good practise to be as precise as possible when defining character classes that are to be repeated. This helps to prevent catastrophic backtracking. Therefore, I'd use [^<]* instead of .*? with the added bonus that it now finds stray characters after the last tag. This would not need the re.DOTALL flag any longer, since [^<] does match newlines.

 "</[^>]+?>[^<>]+?<" 

in ipython:

In [1]: a="<data>  <tag>blar </tag><tagTwo> bo </tagTwo>  some extra   characters not enclosed that I want to remove  <anothertag>bbb</anothertag></data>"

In [2]: import re

In [3]: re.sub( "(</[^>]+?>)[^<>]+?<" ,"\\1<",a)
Out[3]: '<data>  <tag>blar </tag><tagTwo> bo </tagTwo><anothertag>bbb</anothertag></data>'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!