java - 将字符串拆分为 2 个相同的单词

标签 java split

我有一个字符串“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,这是第一个捕获组两次,以换行符分隔。

关于java - 将字符串拆分为 2 个相同的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59998253/

相关文章:

javascript - 将字符串拆分为定义长度的部分

c - 如何使用自定义函数 split() 将句子拆分为单个单词?

c# - 不使用 String.Split 方法拆分字符串不会返回正确的结果

python - 从字符串中提取键和值

java - 作业参数正在被缓存

regex - Python3 - 处理连字符的单词 : combine and split

java - 如何用正则表达式替换最后一个字符为特殊字符的单词

java - 将应用程序从 tomcat 移植到 glassfish

Java:调用另一个类中的方法

java - 如何将相同的有效载荷发送到 mule 中的多个组件?