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

Comment utiliser Java RegEx pour correspondre aux caractères alphabétiques

Les lettres alphabétiques (en majuscules et minuscules) et les chiffres (de 0 à9Les caractères de mot sont considérés. Vous pouvez utiliser les métacaractères "\w" pour les correspondre.

Exemple1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Lire une chaîne de l'utilisateur
      System.out.println("Entrez une chaîne");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "^\\w{5";
      //Compilation de l'expression régulière
      Pattern pattern = Pattern.compile(regex);
      //Objet réchappeur de recherche
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match occurred");
      } else {
         System.out.println("Match not occurred");
      }
   }
}

Sortie1

Entrez une chaîne
hello
Match occurred

Sortie2

Entrez une chaîne
#how
Match not occurred

Exemple2

import java.util.Scanner;
public class RegexExample {
   public static void main( String args[] ) {
      //Expression régulière pour accepter du texte
      String regex = "\\w*";
      System.out.println("Entrez une valeur d'entrée: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      boolean bool = input.matches(regex);
      if(bool) {
         System.out.println("match occurred");
      } else {
         System.out.println("match not occurred");
      }
   }
}

Résultat de la sortie

Entrez une valeur d'entrée:
*##&
match not occurred
Vous pourriez aimer