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/

相关文章:

jquery - 单击新 div 时切换另一个 div 的类。查询

javascript - 如何使尺寸调整器可拖动?

java - 迭代匹配器正则表达式 Java

Python删除方括号和它们之间的无关信息

java - 一个微调器中是否可以有两种不同的字体大小

JAVA 2D 字符串数组列数

java - BufferedWriter write() 不工作

java - Jsoup 使用 select 时忽略嵌套标签

html - 固定元素内溢出

php - 如何使用 PHP 从 $_SERVER ['HTTP_ACCEPT_LANGUAGE' ] 获取语言值?