Bonjour à tous,
Je cherche à trouver un motif ne contenant pas un motif particulier.
J'ai donc cherché sur google et j'ai entendu parler des lookbehind and lookahead, mais j'avoue ne pas avoir tout compris.
J'ai donc fabriqué un exemple.
Je voudrai par exemple détecté toutes les chaines commençant par
un mot autre que sex ou sexAt et se terminant par birth.
dateatBirth serait valide, et sexBirth invalide.
J'ai donc trouvé cet regex et j'avoue ne pas comprendre.
A quoi sert le \b (boundary word....?) et pourquoi on double le \\.?
Pourquoi je dois mettre des \\b devant chaque mot?
Si je ne les mets pas, la regex ne fonctionne pas.
(?!...) signifie t'elle exclure ce motif?
Je vous donne le code complet.
Code : Sélectionner tout - Visualiser dans une fenêtre à part Pattern pattern = Pattern.compile("\\b(?!sex)\\w*birth\\b");
Merci d'avance pour votre aide...
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 import java.io.Console; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args) { Pattern pattern = Pattern.compile("\\b(?!sex|sexat)\\w*birth\\b"); Matcher matcher = pattern.matcher("sexbirth); boolean found = false; while (matcher.find()) { console.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end()); found = true; } if (!found) { console.format("No match found.%n"); } }
Emmanuel
Partager