我正在使用 "\\b(\\w+)(\\W+\\1\\b)+"
和 input = input.replaceAll(regex, "$1");
来查找字符串中的重复单词并删除重复。例如,输入字符串为 "for for for" 将变成 "for"。
但是它无法将 "Hello hello" 转换为 "Hello",即使我已经使用了 Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
我可以通过使用 "(?i)\\b(\\w+)(\\W+\\1\\b)+"
来纠正它,但我想知道为什么需要这样做?为什么在已经指定 Pattern.CASE_INSENSITIVE 的情况下还要使用 (?i) 标志?
以下是完整的代码:
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DuplicateWords {
public static void main(String[] args) {
String regex = "\\b(\\w+)(\\W+\\1\\b)+";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Scanner in = new Scanner(System.in);
int numSentences = Integer.parseInt(in.nextLine());
while (numSentences-- > 0) {
String input = in.nextLine();
Matcher m = p.matcher(input);
// Check for subsequences of input that match the compiled pattern
while (m.find()) {
input = input.replaceAll(regex, "$1");
}
// Prints the modified sentence.
System.out.println(input);
}
in.close();
}
}
(?i)
与将其放置在开头具有相同的效果,这与使用CASE_INSENSITIVE
相同,因为捕获的组是不区分大小写的。一个更好的例子可能是像([ABC])(?i)\1
这样的东西,它与(?i)([ABC])\1
不同。 - BohemianPattern/Matcher
正确使用replaceAll
。 - anubhava