简体   繁体   中英

Can't iterate through Matcher

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM