Java String.replaceAll()引用最新找到的组 [英] Java String.replaceAll() refer the latest found group
问题描述
Javadoc说$ 1,$ 2等可以用来引用匹配组,但是当使用 String.replaceAll()$ c时,如何在替换字符串中引用最新找到的组$ C>?
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。有一个字符串aaabbbaa
和一个正则表达式a +
,我希望能够做到像 s.replaceAll(a +,$ \ n)
获取aaa \\\
,但是Java给了我
bbbaa \ n非法组引用
。
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
.
推荐答案
s.replaceAll((a +),$ 1\ n)
应该有效:
jshell> String s = "aaabbbaa"
s ==> "aaabbbaa"
jshell> s.replaceAll("(a+)", "$1\n")
$2 ==> "aaa\nbbbaa\n"
正如评论中所指出的,你将拥有在正则表达式中标记捕获组。这就是括号(...)
的作用。然后,您必须使用 $ 1
引用该捕获组,这是第一个捕获组。 $ 0
将是整场比赛(也在评论中指出),但只是 $
将无效。
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.
这篇关于Java String.replaceAll()引用最新找到的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!