【发布时间】: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 标签:
<NodeID>(.+?)<\/NodeID>
编辑:
这是我的 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