J'utilise "\b(\w+)(\W+\1\b)+"
de même que input = input.replaceAll(regex, "$1");
pour trouver les mots en double dans une chaîne et supprimer les doublons. Par exemple, la chaîne input = "for for for" deviendrait "for".
Cependant, il ne parvient pas à transformer "Hello hello" en "Hello" même si j'ai déjà utilisé Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Je peux le corriger en utilisant "(?i)\b(\w+)(\W+\1\b)+"
mais je veux savoir pourquoi c'est nécessaire? Pourquoi dois-je utiliser l'indicateur (? I) alors que j'ai déjà spécifié Pattern.CASE_INSENSITIVE?
Voici le code complet pour plus de clarté:
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();
}
}
Réponses:
2 pour la réponse № 1Votre problème est que vous définissez une expression rationnelle avec CASE_SENSITIVE
marquer mais ne pas l'utiliser correctement dans replaceAll
méthode.
Vous pouvez aussi utiliser (?i)
au milieu de l'expression rationnelle pour ignorer la correspondance de casse de référence arrière 1
comme ça:
String repl = "Hello hello".replaceAll("\b(\w+)(\W+(?i:\1)\b)+", "$1");
//=> Hello
Et puis utiliser Matcher.replaceAll
plus tard.
Code de travail:
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();
}
}