java - 正则表达式用于提取标签之间的文本而不是标签

标签 java html regex tags nodes

我有以下文本:

<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我不想要的标签:

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

编辑:

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

    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));
        }
    }

最佳答案

简单。这是因为您获取了所有结果,而不仅仅是第 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 - 正则表达式用于提取标签之间的文本而不是标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36803854/

相关文章:

java - Spring Boot/Thymeleaf/Hibernate : Sessionfactory Bean with Java Annotations

javascript - 用一个链接激活两个 jQuery 函数

javascript - 为什么我的 onclick 不覆盖之前执行的 js 函数?

Java信号量+调用acquire()时不持有同步锁

java - 使用 Spring 加载显示 NPE 的 java 属性文件

javascript - 如何使Jquery-UI按钮控件组突出显示所选项目?

javascript - jquery match() 变量插值 - 复杂的正则表达式

javascript - Javascript正则表达式:字符串中的9或12位数字

javascript - 有关了解正则表达式的几个问题

java - 防止Http访问api