[英]Python non-greedy regex to clean xml
我有一個“ xml文件”文件,其中包含一些不需要的字符
<data>
<tag>blar </tag><tagTwo> bo </tagTwo>
some extra
characters not enclosed that I want to remove
<anothertag>bbb</anothertag>
</data>
我認為以下非貪婪替換將刪除<sometag></sometag>
中未正確裝入的字符
re.sub("</([a-zA-Z]+)>.*?<","</\\1><",text)
^ ^ ^ ^ text is the xml txt.
remember tag, | | put tag back without and reopen next tag
read everything until the next '<' (non-gready)
這個正則表達式似乎只在</tag>[[]]<tagTwo>
找到用[[]]
指示的位置。我在做什么錯?
編輯:解決了這個問題的動機(請參閱注釋,我在xml文件中有一個流浪&導致其無法解析-與我要刪除的字符無關)。 但是,我仍然對正則表達式是否可能(以及我的嘗試有什么問題)感到好奇,因此我不刪除該問題。
點不匹配換行符,除非您指定re.DOTALL
標志。
re.sub("</([a-zA-Z]+)>.*?<","</\\1><",text, flags=re.DOTALL)
應該工作正常。 (如果不是,則我的python出錯了,不是正則表達式。請更正。)
我認為,在定義要重復的字符類時,盡可能精確是一種好習慣。 這有助於防止災難性的回溯 。 因此,我將使用[^<]*
代替.*?
加上額外的好處,它現在可以在最后一個標記之后找到流浪字符。 因為[^<]
確實與換行符匹配,所以不再需要re.DOTALL
標志。
"</[^>]+?>[^<>]+?<"
在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>'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.