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

Carattere di metaespressione re {n} nell'espressione regolare Java

L'espressione interna / carattere speciale "re {n}" corrisponde esattamente all'apparizione n dell'espressione precedente.

Esempio 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "to{1}";
      String input = "Welcome to w3codebox";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Numero di corrispondenze: " + count);
   }
}

Risultato dell'output

Numero di corrispondenze: 2

Esempio 2

Seguendo il programma Java che legge l'età dell'utente, esso accetta solo un numero di due cifre.

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 = "\\d{2}";
      System.out.println("Inserisci la tua età:");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      if(m.matches()) {
         System.out.println("Il valore di età è accettato");
      } else {
         System.out.println("Il valore di età non è accettato");
      }
   }
}

Output 1

Inserisci la tua età:
25
Il valore di età è accettato

Output 2

Inserisci la tua età:
2252
Il valore di età non è accettato

Output 3

Inserisci la tua età:
venti
Il valore di età non è accettato
Ti potrebbe interessare