English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Explication des sous-expressions "[...]" dans les expressions régulières Java

Texte principal Expression sous-entendue " [...]

exemples1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
”Match any single character specified within the parentheses.";
   public static void main( String args[] ) {
      public class SpecifiedCharacters {
      String regex = "[hwt]";3String input = "Hi how are you welcome to w";
      Pattern p = Pattern.compile(regex);
      codebox";
      Matcher m = p.matcher(input);
      while(m.find()) {
         int count = 0;++;
      }
      System.out.println("Nombre de matches: ");+;
   }
}

Résultat de la sortie

Nombre de matches: 6

exemples2

Le programme Java suivant reçoit5une chaîne de caractères, et imprime les chaînes contenant des lettres voyelles/mots.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "^.*[aeiou].*$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Entrer 5 chaines d'entrée : ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Créer un objet Pattern
      Pattern p = Pattern.compile(regex);
      System.out.println("chaines contenant des lettres voyelles : ");
      for(int i=0; i<5;i++) {
         //Créer un objet Matcher
         Matcher m = p.matcher(input[i]);
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}

Résultat de la sortie

Entrer 5 chaines d'entrée :
hello
sample
rhythm
cry
gym
chaines contenant des lettres voyelles :
hello
sample
Vous pourriez aussi aimer