代码之家  ›  专栏  ›  技术社区  ›  Brian Lowe

regex用于处理xml标记-需要帮助

  •  -4
  • Brian Lowe  · 技术社区  · 8 年前

    我有一些伪XML,我正在尝试清理,我大部分时间都在清理,但在标记中的大小写有问题。

    我的消息来源是这样的…

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
      <float_node>1.0</float_node>
      <text_node>Pack My Box</text_node>
      <UPPER_NODE>With Five Dozen</UPPER_NODE>
      <MiXeD_NoDe>SCSG1</MiXeD_NoDe>
      <!-- Comment should not be changed -->
      <GRANDPARENT>
        <PARENT>
          <Child1>Liquor Jugs</Child1>
          <Child2 with-attribute="Pangrams">Jackdaws Love</Child2>
        </PARENT>
        <PARENT>
          <Child1>My Big Sphinx</Child1>
          <Child2 with-attribute="Are Great">Of Gold</Child2>
        </PARENT>
      </GRANDPARENT>
    </root>
    

    但我想要的是…

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
      <float_node>1.0</float_node>
      <text_node>Pack My Box</text_node>
      <upper_node>With Five Dozen</upper_node>
      <mixed_node>SCSG1</mixed_node>
      <!-- Comment should not be changed -->
      <grandparent>
        <parent>
          <child1>Liquor Jugs</child1>
          <child2 with-attribute="Pangrams">Jackdaws Love</child2>
        </parent>
        <parent>
          <child1>My Big Sphinx</child1>
          <child2 with-attribute="Are Great">Of Gold</child2>
        </parent>
      </grandparent>
    </root>
    

    到目前为止我有这个模式…

    <(.+)( .+)?>(.*)<\/\1>
    

    这个替代品…

    <\L$1$2>$3</\L$1>
    

    但是输出是错误的…

    <?xml version="1.0" encoding="UTF-8"?>
    <root>
      <float_node>1.0</float_node>
      <text_node>pack my box</text_node>
      <upper_node>with five dozen</upper_node>
      <mixed_node>scsg1</mixed_node>
      <data_format>excel</data_format>
      <!-- Comment should not be changed -->
      <GRANDPARENT>
        <PARENT>
          <child1>liquor jugs</child1>
          <child2 with-attribute="pangrams">jackdaws love</child2>
        </PARENT>
        <PARENT>
          <child1>my big sphinx</child1>
          <child2 with-attribute="are great">of gold</child2>
        </PARENT>
      </GRANDPARENT>
    </root>
    

    尽管替换字符串有$2和$3两个不同且未经更改,但\l小写将应用于标记内容和属性以及标记。

    嵌套节点被忽略。只改变最里面的节点。我应该如何管理层次结构?

    谁能告诉我我的模式或替代在哪里失败?

    我正在使用regex101帮助构建regex模式和测试… https://regex101.com/r/Oeshto/3

    (由于我的首选编辑器(vscode)不处理所需的转换,所以我使用notepad++来完成实际工作。)

    1 回复  |  直到 8 年前
        1
  •  0
  •   davidbl    8 年前

    以下是满足您需要的正则表达式。我相信一些前注册巫师可以优化或使这些更好,但他们似乎完成了工作。(编辑,我已经删除了我的建议在梨包装,因为这完全是胡说八道,当你要求一个正则表达式只)

    Regular Expression.: /(<\/?[^!][^>]+)/g  ( Change all tags+attributes )
    Regular Expression.: /(<\w+|<\/\w+)/g    ( Change only tags )
    Substitution.......: \L$1
    

    不要忘记全局标志,这样它在第一个结果后就不会返回。 这应该与所有标签匹配。