gpt4 book ai didi

Java正则表达式从字符串中删除重复的子字符串

转载 作者:搜寻专家 更新时间:2023-11-01 02:21:48 25 4
gpt4 key购买 nike

我正在尝试构建一个正则表达式来“减少”Java 字符串中重复的连续子字符串。例如,对于以下输入:

The big black dog big black dog is a friendly friendly dog who lives nearby nearby.

我想得到以下输出:

The big black dog is a friendly dog who lives nearby.

这是我目前的代码:

String input = "The big black dog big black dog is a friendly friendly dog who lives nearby nearby.";

Pattern dupPattern = Pattern.compile("((\\b\\w+\\b\\s)+)\\1+", Pattern.CASE_INSENSITIVE);
Matcher matcher = dupPattern.matcher(input);

while (matcher.find()) {
input = input.replace(matcher.group(), matcher.group(1));
}

对于除了句子末尾之外的所有重复子字符串,这都很好:

The big black dog is a friendly dog who lives nearby nearby.

我知道我的正则表达式在子字符串中的每个单词后都需要一个空格,这意味着它不会捕获带有句点而不是空格的情况。我似乎找不到解决方法,我尝试使用捕获组并更改正则表达式以查找空格或句点而不仅仅是空格,但此解决方案仅在有子字符串的每个重复部分之后的句号(“nearby.nearby.”)。

有人能指出我正确的方向吗?理想情况下,此方法的输入将是短段落,而不仅仅是一行。

最佳答案

你可以使用

input.replaceAll("([ \\w]+)\\1", "$1");

参见 live demo:

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String input = "The big black dog big black dog is a friendly friendly dog who lives nearby nearby.";

Pattern dupPattern = Pattern.compile("([ \\w]+)\\1", Pattern.CASE_INSENSITIVE);
Matcher matcher = dupPattern.matcher(input);

while (matcher.find()) {
input = input.replaceAll("([ \\w]+)\\1", "$1");
}
System.out.println(input);

}
}

关于Java正则表达式从字符串中删除重复的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38683612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com