Python非贪婪正则表达式清除xml [英] Python non-greedy regex to clean xml

查看:116
本文介绍了Python非贪婪正则表达式清除xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个"xml文件"文件,其中包含一些不需要的字符

I have an 'xml file' file that has some unwanted characters in it

<data>
  <tag>blar </tag><tagTwo> bo </tagTwo>
  some extra 
  characters not enclosed that I want to remove
  <anothertag>bbb</anothertag>
</data>

我认为以下非贪婪替换将删除<sometag></sometag>

I thought the following non-greedy substitution would remove the characters that were not properly encased in <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>中找到用[[]]指示的位置 我在做什么错了?

This regex seems only to find the position indicated with the [[]] in </tag>[[]]<tagTwo> What am I doing wrong?

这个问题的动机已经解决(请参阅注释,我在xml文件中有一个流浪&导致它无法解析-与我要删除的字符无关).但是,我仍然对正则表达式是否可能(以及我的尝试出了什么问题)感到好奇,因此我不删除该问题.

The motivation for this question has been solved (see comments, I had a stray & in the xml file which was causing it not to parse - it had nothing to do with the characters that I want to delete). However, I am still curious as to whether the regex is possible (and what was wrong with my attempt) and so I don't delete the question.

推荐答案

除非指定re.DOTALL标志,否则点不匹配换行符.

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

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

应该可以正常工作. (如果不是,则我的python出错了,不是正则表达式.请更正.)

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

我认为在定义要重复的字符类时,尽可能精确是一种很好的做法.这有助于防止灾难性的回溯.因此,我将使用[^<]*而不是.*?并获得额外的好处,因为它现在可以在最后一个标记之后找到流浪字符.因为[^<]确实与换行符匹配,所以不再需要re.DOTALL标志.

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.

这篇关于Python非贪婪正则表达式清除xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆