【问题标题】:Ignoring newlines with regex in xml [duplicate]在xml中使用正则表达式忽略换行符[重复]
【发布时间】:2019-05-31 17:31:46
【问题描述】:

这是一个非常特定用途的项目。

我正在尝试查找如何从 xml 中查找任何空文本并将其替换为消息。

regex = re.compile(r'>\s*</')


replaced = re.sub(regex, ">[!] JSON value does not exist, Check your Json!</", temp)

例如文件名是空白的

        <file>               
            <fileType>Mezza</fileType>
            <fileName></fileName>
            <segments>0000</segments>
        </file>

输出将是:

         <file>               
            <fileType>Mezza</fileType>
            <fileName>[!] value does not exist!</fileName>
            <segments>0000</segments>
        </file>

但是我得到了其他有空格和换行符的部分我不想收到这条消息,两个标签名称不同,有一个新行,它们是结束标签我如何在正则表达式中实现这个?:

</fileName>[!] value does not exist!</file>

【问题讨论】:

  • 使用空格代替\s
  • 我需要确保这些标签中有文字。
  • 我以为您正在尝试检测标签中是否只有空格。
  • 使用真正的 XML 解析器或 XPath 来解析 XML,而不是正则表达式。

标签: regex xml python-3.x regex-group regex-greedy


【解决方案1】:

也许,我们可能有的另一个选择是只找到filename,并替换标签内我们想要的内容,可能是这样的表达式:

(<fileName>)(.+)?(<\/fileName>)

如果我正确理解了问题。

Demo 1

如果我们有完全空的标签,这个表达式可能会起作用:

(>)()(<\/)

Demo 2

如果我们将有空标签和带有水平空格的标签,那么我们会将其扩展为:

(>)(|[^\S\r\n]+)(<\/)

Demo 3

测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(<fileName>)(.+)?(<\/fileName>)"

test_str = ("        <file>               \n"
    "            <fileType>Mezza</fileType>\n"
    "            <fileName></fileName>\n"
    "            <segments>0000</segments>\n"
    "        </file>")

subst = "\\1[!] value does not exist!\\3"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

【讨论】:

  • 感谢 Emma 的回复,但文件名就是一个例子。还有其他标签,这就是问题所在。
【解决方案2】:

使用[ \t]* 而不是\s*。这将匹配空格和制表符,但不匹配换行符。所以代码应该是:

regex = re.compile(r'>[ \t]*</')

DEMO

【讨论】:

  • python是否接受\h水平空格?
  • 查看演示,它正在打印消息。
  • 解析 XML 并检查那里的值可能会更好,而不是使用正则表达式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 2019-10-18
  • 2012-10-22
  • 2019-11-17
  • 1970-01-01
相关资源
最近更新 更多