正则表达式处理XML标记 - 需要帮助

时间:2018-06-12 09:11:21

标签: regex xml

我有一些伪XML,我试图清理它,而且我大部分都在那里,但是标签中的套管存在问题。

我的来源看起来像这样......

findElement(By.name("AddSchool"))

但我想要的是......

<?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>

\ L \ smallcasing正在应用于标记内容和属性以及标记,即使替换字符串具有$ 2和$ 3不同且未更改。

嵌套节点被忽略了。仅更改最内层节点。我该如何管理层次结构?

有人能告诉我我的模式或替换失败了吗?

我使用Regex101获取有关构建正则表达式模式和测试的帮助...... https://regex101.com/r/Oeshto/3

(我使用Notepad ++来完成实际工作,因为我的首选编辑器(VSCode)没有处理所需的\ L转换。)

1 个答案:

答案 0 :(得分:0)

以下是适合您需求的正则表达式。我敢肯定一些注册向导可以优化或使这些更好,但他们似乎完成了工作。 (已编辑,我删除了我对PEAR包的建议,因为当你要求使用正则表达式时,这完全是胡说八道)

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

不要忘记Global标志,以便在第一次结果后不会返回。 这应该匹配所有标签。