【问题标题】:Remove select characters from xml tags using regex使用正则表达式从 xml 标签中删除选择的字符
【发布时间】:2018-05-18 20:09:50
【问题描述】:

我正在尝试仅从 xml 标签中删除选择的字符 + 后面的任何数字 + 进行中的 : .. 例如: <ns2:projectArea alias= 应该看起来像 <projectArea alias= <ns9:name> 应该看起来像 <name>

基本上,数字将是随机的(从 1 到 9 中的任何数字),并且总会有一个必须删除的进程 :

到目前为止我所拥有的是:

import argparse
import re

# Initiates argument
parser = argparse.ArgumentParser()

parser.add_argument("--input", "-i", help="Set the input xml to clean up")
parser.add_argument("--output", "-o", help="Set the output xml location")

args = parser.parse_args()
inputfile = args.input
outputfile = args.output
if args.input:
  print("inputfile location is %s" % args.input)
if args.output:
  print("outputfile location is %s" % args.output)
# End argument

text = re.sub('<[^<]+>', "", open(inputfile).read())
with open(outputfile, "w") as f:
    f.write(text)

这段代码就是问题所在:'&lt;[^&lt;]+&gt;' 它会删除整个标签,所以如果我以后需要搜索文本,基本上必须搜索纯文本而不是标签。

我可以用什么替换'&lt;[^&lt;]+&gt;' 将删除ns + 后面的数字(不管它可能是什么数字)+ 后面的:

【问题讨论】:

  • /[a-zA-Z]+[0-9]: 但是这是假设您只想搜索一位数字
  • 停止尝试使用正则表达式解析 XML/HTML,并改用 DOM 解析器。 (并且 选择字符 被称为命名空间。)
  • r'&lt;([^:]+):.*?&gt;' 或允许在再次转储之前杀死命名空间的解析器
  • @Matt.G 实际上工作得几乎完美.. 但是,带有/ 的结束标签不会被删除,除非我将它添加到节中,例如:(?&lt;=&lt;)/ns[0-9]+:(?=[^&gt;]*?&gt;) 有没有办法让它删除/ns...(如果存在)?

标签: python regex xml


【解决方案1】:

这可能是由于正则表达式而发生的。尝试改用这个正则表达式:

   text = re.sub('^<[a-zA-Z0-9]+:','<',open(inputfile).read())

【讨论】:

    【解决方案2】:

    这行得通:

    查找r"&lt;(?:(?:(/?)\w+[1-9]:(\w+\s*/?))|(?:\w+[1-9]:(\w+\s+(?:\"[\S\s]*?\"|'[\S\s]*?'|[^&gt;]?)+\s*/?)))&gt;"
    替换&lt;$1$2$3&gt;

    https://regex101.com/r/yRhMI9/1

    可读版本:

     <
     (?:
          (?:
               ( /? )                        # (1)
               \w+ [1-9] :
               ( \w+ \s* /? )                # (2)
          )
       |  (?:
               \w+ [1-9] :
               (                             # (3 start)
                    \w+ \s+ 
                    (?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]? )+
                    \s* /?
               )                             # (3 end)
          )
     )
     >
    

    【讨论】:

      【解决方案3】:

      正则表达式:(?:(?&lt;=&lt;)|(?&lt;=&lt;\/))(ns[0-9]+:)(?=[^&gt;]*?&gt;)

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-05
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        • 2018-09-13
        相关资源
        最近更新 更多