Reputation: 602
I'm trying to do this:
String regex= "^[\\d\\D]*([{]([^{}]+)[}])[\\d\\D]*$";
Matcher groupMatcher = Pattern.compile(regex).matcher(command);
int counter = 0;
while(groupMatcher.find()){
counter++;
}
//print counter
And I always get counter 1 and only resulting match for "{name} {do something}". No matter how I change it, here for instance I get {do something} being matched.
I want to iterate through all of the matches. How can I do it?
Upvotes: 0
Views: 116
Reputation: 121760
First you should fix your [\d\D]
: \D
is \d
's complement, which means it will match any character which \d
doesn't. Basically, this character class is equivalent to .
...
Given that, let's replace the character class with its equivalent:
^.*(\{([^{}]+)\}).*$
After the first .*
, the regex will have already matched all your input string. However, the matching is not complete: a {
needs to be matched.
Therefore, the .*
gives back character by character to the regex engine unless it reaches a {
-- and that will be the {
before {do something}
.
Your first capturing group will therefore contain {do something}
.
The first thing is therefore to fix your character class: I don't know what you meant when you wrote [\d\D]
but it was certainly not "match any character"!
Here is a regex which will try and match all arguments within curly braces:
\{([^{}]+)\}
Use this regex in a Matcher
and you'll have your matches (with m.group(1)
).
Upvotes: 3