【问题标题】:Regex for extracting text between Tags but not the tags用于在标签之间提取文本而不是在标签之间提取文本的正则表达式
【发布时间】:2016-08-16 16:14:23
【问题描述】:

我有以下文字:

<Data>
    <xpath>/Temporary/EIC/SpouseSSNDisqualification</xpath>
    <Gist>AllConditionsTrue</Gist>
    <Template>
        <Text id="1">Your spouse is required to have a Social Security number instead of an ITIN to claim this credit.  This is based on the IRS rules for claiming the Earned Income Credit.</Text>
    </Template>
</Data>
<Data>
    <xpath>/Temporary/EIC/SpouseSSNDisqualification</xpath>
    <Gist>AllConditionsTrue</Gist>
    <Template>
        <Text id="1">Your spouse has the required Social Security number instead of an ITIN to claim this credit.  This is based on the IRS rules for claiming the Earned Income Credit.</Text>
    </Template>
</Data>

我想提取xpath 标签之间的数据,而不是标签本身。

输出应该是:

/Temporary/EIC/SpouseSSNDisqualification

/Temporary/EIC/SpouseSSNDisqualification

这个正则表达式似乎给了我所有的文本,包括我不想要的 xpath 标签:

&lt;NodeID&gt;(.+?)&lt;\/NodeID&gt;

编辑:

这是我的 Java 代码,但我不确定这是否会增加我的问题的价值:

    try {
        String xml = FileUtils.readFileToString(file);
        Pattern p = Pattern.compile("<xpath>(.+?)<\\/xpath>");
        Matcher m = p.matcher(xml);

        while(m.find()) {
            System.out.println(m.group(0));
        }
    }

【问题讨论】:

  • 如果你把你试过的java代码也放上问题会好很多
  • Don't parse XML with regex(答案是 HTML,但它是同一个问题)
  • 您确实使用(xxx) 捕获组捕获了您想要的内容,因此只需调用group(1) 即可使用它。 group(0) 返回整个匹配模式,而不仅仅是捕获的部分。 --- 虽然我同意@AlexHall:不要使用正则表达式从 XML 中提取文本。使用 XML 解析器。
  • @Andreas 感谢使用第 1 组就像一个魅力
  • 您也可以使用 XPath。不是节点名,而是一个叫做 XPath 的方法

标签: java html regex tags nodes


【解决方案1】:

您可以尝试使用前瞻和后瞻方法:

Pattern pattern = Pattern.compile("(?<=<xpath>)(.*?)(?=</xpath>)");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    String group = matcher.group();
    System.out.println(group);
}

我相信这是一种更清洁的方法。

【讨论】:

    【解决方案2】:

    简单。这是因为您获取了所有结果,而不仅仅是第 1 组的值。

    String nodestr = "<xpath>/Temporary/EIC/SpouseSSNDisqualification</xpath>";
    String regex = "<xpath>(.+?)<\/xpath>";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(nodestr);
    if (matcher.matches()) {
        String tag_value = matcher.group(1); //taking only group 1
        System.out.println(tag_value); //printing only group 1
    }
    

    【讨论】:

    • 不要转义/。它在 Java 正则表达式中没有任何意义,因此不需要转义。
    • 谢谢@Aminah Nuraini
    猜你喜欢
    • 2013-02-08
    • 2011-09-27
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多