Java String.replaceAll() refer the latest found group

眉间皱痕 提交于 2019-12-04 05:40:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!