Créer un tableau de correspondances regex

En Java, j’essaie de renvoyer toutes les correspondances regex à un tableau, mais il semble que vous ne pouvez vérifier que si le motif correspond à quelque chose ou non (booléen). Quelqu’un peut-il m’aider à utiliser une correspondance de regex pour former un tableau de toutes les chaînes correspondant à une expression rationnelle dans une chaîne donnée? Merci!

( La réponse de 4castle est meilleure que la réponse ci-dessous si vous pouvez supposer Java> = 9)

Vous devez créer un matcher et l’utiliser pour trouver des correspondances de manière itérative.

import java.util.regex.Matcher; import java.util.regex.Pattern; ... List allMatches = new ArrayList(); Matcher m = Pattern.comstack("your regular expression here") .matcher(yourSsortingngHere); while (m.find()) { allMatches.add(m.group()); } 

Après cela, allMatches contient les correspondances et vous pouvez utiliser allMatches.toArray(new Ssortingng[0]) pour obtenir un tableau si vous en avez vraiment besoin.


Vous pouvez également utiliser MatchResult pour écrire des fonctions d’assistance afin d’effectuer une boucle sur les correspondances, car Matcher.toMatchResult() renvoie un instantané de l’état du groupe actuel.

Par exemple, vous pouvez écrire un iterator paresseux pour vous laisser faire

 for (MatchResult match : allMatches(pattern, input)) { // Use match, and maybe break without doing the work to find all possible matches. } 

en faisant quelque chose comme ça:

 public static Iterable allMatches( final Pattern p, final CharSequence input) { return new Iterable() { public Iterator iterator() { return new Iterator() { // Use a matcher internally. final Matcher matcher = p.matcher(input); // Keep a match around that supports any interleaving of hasNext/next calls. MatchResult pending; public boolean hasNext() { // Lazily fill pending, and avoid calling find() multiple times if the // clients call hasNext() repeatedly before sampling via next(). if (pending == null && matcher.find()) { pending = matcher.toMatchResult(); } return pending != null; } public MatchResult next() { // Fill pending if necessary (as when clients call next() without // checking hasNext()), throw if not possible. if (!hasNext()) { throw new NoSuchElementException(); } // Consume pending so next call to hasNext() does a find(). MatchResult next = pending; pending = null; return next; } /** Required to satisfy the interface, but unsupported. */ public void remove() { throw new UnsupportedOperationException(); } }; } }; } 

Avec ça,

 for (MatchResult match : allMatches(Pattern.comstack("[abc]"), "abracadabra")) { System.out.println(match.group() + " at " + match.start()); } 

les rendements

 a at 0 b at 1 a at 3 c at 4 a at 5 a at 7 b at 8 a at 10 

Java rend la regex trop compliquée et ne suit pas le style perl. Jetez un coup d’oeil à MentaRegex pour voir comment vous pouvez accomplir cela dans une seule ligne de code Java:

 Ssortingng[] matches = match("aa11bb22", "/(\\d+)/g" ); // => ["11", "22"] 

Dans Java 9, vous pouvez maintenant utiliser Matcher#results() pour obtenir un Stream que vous pouvez utiliser pour obtenir une liste / un tableau de correspondances.

 import java.util.regex.Pattern; import java.util.regex.MatchResult; 
 Ssortingng[] matches = Pattern.comstack("your regex here") .matcher("ssortingng to search from here") .results() .map(MatchResult::group) .toArray(Ssortingng[]::new); // or .collect(Collectors.toList()) 

Voici un exemple simple:

 Pattern pattern = Pattern.comstack(regexPattern); List list = new ArrayList(); Matcher m = pattern.matcher(input); while (m.find()) { list.add(m.group()); } 

(Si vous avez plus de groupes de capture, vous pouvez les list.toArray() par leur index en tant qu’argument de la méthode de groupe. Si vous avez besoin d’un tableau, utilisez list.toArray() )

De Java Regex Official Trails :

  Pattern pattern = Pattern.comstack(console.readLine("%nEnter your regex: ")); Matcher matcher = pattern.matcher(console.readLine("Enter input ssortingng to search: ")); 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; } 

Utilisez find et insérez le group résultant dans votre tableau / Liste / peu importe.

  Set keyList = new HashSet(); Pattern regex = Pattern.comstack("#\\{(.*?)\\}"); Matcher matcher = regex.matcher("Content goes here"); while(matcher.find()) { keyList.add(matcher.group(1)); } return keyList;