【发布时间】: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)
这段代码就是问题所在:'<[^<]+>'
它会删除整个标签,所以如果我以后需要搜索文本,基本上必须搜索纯文本而不是标签。
我可以用什么替换'<[^<]+>' 将删除ns + 后面的数字(不管它可能是什么数字)+ 后面的:?
【问题讨论】:
-
/[a-zA-Z]+[0-9]:但是这是假设您只想搜索一位数字 -
停止尝试使用正则表达式解析 XML/HTML,并改用 DOM 解析器。 (并且 选择字符 被称为命名空间。)
-
r'<([^:]+):.*?>'或允许在再次转储之前杀死命名空间的解析器 -
@Matt.G 实际上工作得几乎完美.. 但是,带有
/的结束标签不会被删除,除非我将它添加到节中,例如:(?<=<)/ns[0-9]+:(?=[^>]*?>)有没有办法让它删除/ns...(如果存在)?