0

@id次のような式の中から fromの値を解析しようとしています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

[and]も正規表現文字であるため、エスケープする必要があります。

findそして、 (とは対照的に)やっている場合は、最初と最後にmatches取り出したほうがよいでしょう。.*

正規表現:

"/hrdg:selection\\[@id='(\\d+)'\\]"
于 2013-09-03T10:49:14.847 に答える
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 に答える