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

Comment utiliser Java RegEx pour matcher le début de l'entrée ?

Vous pouvez utiliser le métacaractère "\\ A" pour correspondre au début de l'entrée.

Exemple

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Lecture d'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 = "\\A[0-9];
      //Compilation de l'expression régulière
      Pattern pattern = Pattern.compile(regex);
      //Récupération de l'objet matcher
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      if(matcher.find()) {
         System.out.println("Correspondance trouvée ");
      } else {
         System.out.println("Aucun correspondance trouvé ");
      }
   }
}

Sortie1

Entrez une chaîne
12 texte d'exemple
Correspondance trouvée

Sortie2

Entrez une chaîne
texte d'exemple
Aucun correspondance trouvé
Vous pourriez aussi aimer