问题
Javadoc says $1, $2, etc. can be used to reference the match groups, but how does one reference the latest found group in the replacement string when using String.replaceAll()
?
I.e. there's a string "aaabbbaa"
and a regex "a+"
, and I want to be able to do something like s.replaceAll("a+", "$\n")
to get "aaa\nbbbaa\n"
, but Java gives me the Illegal group reference
.
回答1:
s.replaceAll("(a+)", "$1\n")
should work:
jshell> String s = "aaabbbaa"
s ==> "aaabbbaa"
jshell> s.replaceAll("(a+)", "$1\n")
$2 ==> "aaa\nbbbaa\n"
As pointed out in the comments already, you'll have to mark the capture group in your regular expression. That's what the parentheses (...)
do. Then you'll have to reference that capture group with $1
, which is the first capture group. $0
would be the whole match (also pointed out in the comments), but just $
will not work.
来源:https://stackoverflow.com/questions/47351859/java-string-replaceall-refer-the-latest-found-group