1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public static String removeWordsWithMatcher (String str, String[] words) {
Pattern p = Pattern.compile("\\s*(\\p{L}')?(\\p{L}+)\\s*");
Matcher m = p.matcher(str);
StringBuffer result = new StringBuffer();
// On recherche le mot suivant
while (m.find()) {
// On récupère le mot courant (m.group(2) == le second terme entre parenthèse,
// c-a-d le mot sans les espaces ni apostrophe)
String compare = m.group(2);
boolean matche = false;
// On compare le mot avec la liste des mots à supprimer
for (int i = 0; i < words.length && !matche; i++) {
if (compare.equalsIgnoreCase(words[i])) {
matche = true;
}
}
// Si le mot appartient à la liste des termes à supprimer
if (matche) {
// On le supprime
m.appendReplacement(result,"");
} else {
// Sinon on le laisse tels quel (m.group() == l'ensemble du terme)
m.appendReplacement(result, m.group());
}
}
m.appendTail(result);
return result.toString();
} |
Partager