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

La construction \ d des expressions régulières Java

Expression sous-jacente/Le métacaractère " \ d " qui correspond aux nombres.

exemple1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\\d 24";
      String input = "This is sample text 12 24 56 89 24";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Nombre de correspondances: ");+count);
   }
}

Résultat de la sortie

Nombre de correspondances: 2

exemple2

Voici un exemple de lecture10un programme Java pour trouver des chiffres.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      String regex = "\\d{10";
      Scanner sc = new Scanner(System.in);
      System.out.println("Entrez votre numéro de téléphone (10 chiffres): ");
      String input = sc.nextLine();
      //Créer un objet Pattern
      Pattern p = Pattern.compile(regex);
      //Créer un objet Matcher
      Matcher m = p.matcher(input);
      if(m.find()) {
         System.out.println("OK");
      } else {
         System.out.println("Entrée incorrecte");
      }
   }
}

Sortie1

Entrez votre numéro de téléphone (10 chiffres):
9848022338
OK

Sortie2

Entrez votre numéro de téléphone (10 chiffres):
545
Entrée incorrecte
Vous pourriez aussi aimer