Earlier today I was surprised to realize that matcher.repl开发者_Python百科aceAll("$2")
works whereas matcher.replaceAll(matcher.group(2))
doesn't work (as intended).
I thought that both refer to the same thing: The string matched by the pair of capturing parentheses.
Apparently, there is a subtle difference about which I couldn't find detailed enough documentation.
I found this excellent intro/tutorial referring to both but it failed short of delving deeper into the subtle difference.
Where can I find more information about this?
From API documentation of Matcher.replaceAll:
This method first resets this matcher. It then scans the input sequence looking for matches of the pattern. Characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement method.
This means that $2
will take the value of second group each time a match is found.
On the other hand when you use Matcher.group(2) you use it only once - so replaceAll() takes just plain String with second group from the first match that was found by find()
method.
精彩评论