【问题标题】:RegEx to find multiple tags in specifed order正则表达式以特定顺序查找多个标签
【发布时间】:2015-06-08 21:51:00
【问题描述】:

论坛成员, 我正在使用最新版本的 NotePad++,我需要一个 RegEx 的帮助,它将按照我指定的顺序搜索多个标记的单词。下面是我准备的一个例子:

<first> <second> <third> - 按我需要 RegEx 查找它们的顺序表示三个标签。

<second> <first> <third> - 这些标签不是我需要的顺序,因此我希望 RegEx 在搜索中忽略它们。

<third> <second> <first> <second> <second> - 这些标签不是我需要的顺序,还包括重复的标签,我不需要 RegEx 包含在搜索中。

我已经尝试过这个正则表达式:(first | second | third)

但是,它似乎给了我不想要的额外数据。任何帮助将不胜感激。

【问题讨论】:

  • 为什么不简单地(first second third)?确保顺序,确保所有三个都存在......
  • 这不是有效的 XML。你的意思是<first /> <second /> <third /> 还是<first><second><third>match here</third></second></first>

标签: regex xml notepad++


【解决方案1】:

尝试:

<first>[^<>]*<second>[^<>]*<third>

【讨论】:

  • 与我使用的相比,它似乎更有效。感谢您的帮助。
【解决方案2】:

您在这里遇到了一个难题,因为......从根本上说,XML 很难用正则表达式解析。有一大堆东西构成语义相同(或非常相似)的 XML,它们会破坏正则表达式。

所以真正的答案是“使用 xpath”,它是一个 XML 表达式,它......更像是一个目录路径。作为 perl 中的一个说明性示例(将在 Windows 上运行)。

#!/usr/bin/perl 
use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new( 'pretty_print' => 'indented' )->parse( \*DATA );

foreach my $match ( $twig->root->get_xpath('//first/second/third') ) {
    print $match ->text, "\n";
}

$twig->print;

__DATA__
<root>
<first>
    <second>
        <third>match here</third>
    </second>
</first>
<second>
   <first>
      <third>not a match</third>
   </first>
</second>
<first> <second>
        <third>another match here</third></second>
</first>
<someparent>
   <another>
      <first><second><third>deeper nested match</third></second></first>
   </another>
</someparent>
</root>

//first/second/third 的“xpath”将找到您想要的元素(开头的// 表示“当前的所有后代”)。我认为 Notepad++ 支持 XML 插件。

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多