我有一个字符串“ abcabc”,我想将其拆分并像这样打印:

abc

abc


字符串的代码定义:

String word = "abcabc";

最佳答案

我们可以尝试将String#replaceAll用于单行选项:

String input = "abcabc";
String output = input.replaceAll("^(.*)(?=\\1$).*", "$1\n$1");
System.out.println(output);


打印:

abc
abc


想法是在整个字符串上应用模式,该模式匹配并捕获一定数量,然后在其后跟相同数量。这是根据您的确切输入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')


然后,用$1\n$1代替,它是两次第一个捕获组,并用换行符分隔。

07-28 02:28
查看更多