0

我正在尝试@id从表达式内部解析 的值,xPath例如:

"/hrdg:data/hrdg:meeting[@code='30J7Q']/hrdg:event[@id='2545525']/hrdg:selection[@id='31192111']"

我已经编写了这个正则表达式,并且正在使用以下代码进行匹配:

 Pattern selectionIdPattern = Pattern.compile(".*/hrdg:selection[@id=\'(\\d+)\'].*");
 // Grab the xPath from the XML.
 xPathData = // Loaded from XML..;
 // Create a new matcher, using the id as the data.
 Matcher matcher = selectionIdPattern.matcher(xPathData);
 // Grab the first group (the id) that is loaded.
 if(matcher.find())
 {
     selectionId = matcher.group(1);
 }

但是selectionId不包含 之后的值@id=

期望结果的例子

例如,通过上面的语句,我想得到:

"/hrdg:data/hrdg:meeting[@code='30J7Q']/hrdg:event[@id='2545525']/hrdg:selection[@id='31192111']"

Data I want: 31192111
4

5 回答 5

2

You need to escape the [ and ], as these are also regex characters.

And if you're doing find (as opposed to matches), you may as well take out .* at the start and the end.

Regex:

"/hrdg:selection\\[@id='(\\d+)'\\]"
于 2013-09-03T10:49:14.847 回答
2
String s = "/hrdg:data/hrdg:meeting[@code='30J7Q']/hrdg:event[@id='2545525']/hrdg:selection[@id='31192111']";
Pattern pattern = Pattern.compile("(?<=selection\\[@id=')\\w+(?='])");
Matcher matcher = pattern.matcher(s);
matcher.find();
System.out.println(matcher.group());

输出:31192111

于 2013-09-03T10:48:22.297 回答
1

您需要转义字符类字符[]中使用的正则表达式Pattern selectionIdPattern

String xPathData = "/hrdg:data/hrdg:meeting[@code='30J7Q']/hrdg:event[@id='2545525']/hrdg:selection[@id='31192111']";
Pattern selectionIdPattern = Pattern.compile(".*/hrdg:selection\\[@id=\'(\\d+)\'\\]");
Matcher matcher = selectionIdPattern.matcher(xPathData);
if (matcher.find()) {
     String selectionId = matcher.group(1); // now matches 31192111
     ...
}

由于Matcher#find部分匹配,通配符.*也可以从表达式中删除

于 2013-09-03T10:46:09.453 回答
1

[] 字符表示匹配介于两者之间的字符。您需要转义方括号。

于 2013-09-03T10:48:03.533 回答
1

如果你的所有字符串都这样,你可以试试这个

 String str="/hrdg:data/hrdg:meeting[@code='30J7Q']/
    hrdg:event[@id='2545525']/hrdg:selection[@id='31192111']";
 int index=str.lastIndexOf("@id");
 System.out.println(str.substring(index+5,str.length()-2));
于 2013-09-03T10:48:04.443 回答