我在用着"\\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();
}
}
你的问题是你正在定义一个正则表达式CASE_SENSITIVE
标志但没有正确使用它replaceAll
方法。
您还可以使用(?i)
在正则表达式的中间,用于忽略反向引用的大小写匹配\1
像这样:
String repl = "Hello hello".replaceAll("\\b(\\w+)(\\W+(?i:\\1)\\b)+", "$1");
//=> Hello
然后使用Matcher.replaceAll
later.
工作代码:
public class DuplicateWords {
public static void main(String[] args) {
String regex = "\\b(\\w+)(\\W+(?i:\\1)\\b)+";
Pattern p = Pattern.compile(regex);
// OR this one also works
// 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
if (m.find()) {
input = m.replaceAll("$1");
}
// Prints the modified sentence.
System.out.println(input);
}
in.close();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)