christopher
christopher

Reputation: 27336

Matching numbers in String using Regex

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

Upvotes: 0

Views: 100

Answers (5)

Reimeus
Reimeus

Reputation: 159754

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

Upvotes: 1

user2742695
user2742695

Reputation:

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

Upvotes: 2

Bernhard Barker
Bernhard Barker

Reputation: 55589

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+)'\\]"

Upvotes: 2

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35547

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

Upvotes: 1

David Sainty
David Sainty

Reputation: 1498

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

Upvotes: 1

Related Questions