0

I'm attempting to parse the value of @id from inside an xPath expression like:

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

I have written this regular expression, and am using thefollowing code for matching:

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

However selectionId does not contain the value after @id=.

Example of Desired Outcome

For example, with the above statement, I want to get:

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

Data I want: 31192111
0

5 Answers 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+)'\\]"
Sign up to request clarification or add additional context in comments.

1 Comment

Pattern.compile("/hrdg:event\\[@id='(\\d+)'\\]/") since you have to escape the \ to be valid in a String. ' needs no escaping.
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());

Output : 31192111

Comments

1

The [] characters are indicating to match a character out of those in between. You'll need to escape the square brackets.

Comments

1

If your all Strings like this, you can try this

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

Comments

1

You need to escape the character class characters [ and ] in the regular expression used in 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
     ...
}

Since Matcher#find does partial matches, the wilcard characters .* can also be removed from the expression

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.