matches()
ne retourne true si la chaîne est mis en correspondance.
find()
va essayer de trouver la prochaine apparition au sein de la sous-chaîne correspondant à l'expression régulière. Note de l'accent mis sur "suivant". Cela signifie que le résultat de l'appel d' find()
plusieurs fois pourrait ne pas être la même. En outre, en utilisant find()
vous pouvez appeler start()
pour renvoyer la position de la sous-chaîne a été trouvée.
final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());
System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
Sortie:
Trouvé: faux
Trouvé: vrai - position 4
Trouvé: vrai - position 17
Trouvé: vrai - position 20
Trouvé: faux
Trouvé: faux
Correspondance: faux
-----------
Trouvé: vrai - position 0
Trouvé: faux
Trouvé: faux
Correspondance: vrai
Correspondance: vrai
Correspondance: vrai
Correspondance: vrai
Alors, soyez prudent lors de l'appel d' find()
plusieurs fois si l' Matcher
objet n'a pas été réinitialisé, même si la regex est entouré d' ^
et $
pour correspondre à la chaîne complète.