Java String.replaceAll() refer the latest found group

后端 未结 1 517
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 00:44

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

1条回答
  •  无人共我
    2021-01-26 01:24

    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.

    0 讨论(0)
提交回复
热议问题