我有一个字符串“abcabc”,我想拆分它并像这样打印:
abc
abc
Run Code Online (Sandbox Code Playgroud)
字符串的代码定义:
String word = "abcabc";
Run Code Online (Sandbox Code Playgroud)
我们可以尝试使用String#replaceAll单行选项:
String input = "abcabc";
String output = input.replaceAll("^(.*)(?=\\1$).*", "$1\n$1");
System.out.println(output);
Run Code Online (Sandbox Code Playgroud)
这打印:
abc
abc
Run Code Online (Sandbox Code Playgroud)
这个想法是将一个模式应用于匹配并捕获一些数量的整个字符串,然后跟随相同的数量直到结束。这是针对您的确切输入执行的模式解释abcabc:
(.*) match 'abc'
(?=\1$) then lookahead and assert that what follows to the end of the string
is exactly another 'abc'
.* consume, but do not match, the remainder of the input (which must be 'abc')
Run Code Online (Sandbox Code Playgroud)
然后,我们用 替换$1\n$1,这是第一个捕获组两次,用换行符分隔。
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |