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

Comment utiliser Java RegEx pour correspondre à la fin de l'entrée ?

Vous pouvez utiliser le métacaractère "\\z" pour correspondre à la fin 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 de la chaîne depuis l'utilisateur
      System.out.println("Entrez une chaîne");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "[0-9]\\z";
      //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("Correspondance non trouvée ");
      }
   }
}

Sortie1

Entrez une chaîne
Texte d'exemple
Correspondance non trouvée

Sortie2

Entrez une chaîne
Texte d'exemple 23
Correspondance trouvée
Vous pourriez aussi aimer