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

Carattere di espansione re {n, m} negli espressioni regolari in Java

Espressione secondaria/simbolo " re {n, m} Corrispondenze di almeno n e massimo m con l'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 = "xyy{2,4}";
      String input = "xxyyzxxyyyyxyyzxxyyzz";
      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: 1

Esempio 2

Il seguente programma Java legge il valore del nome dall'utente e consente solo 1 a 20 caratteri.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[] ) {
      //Espressione regolare per abbinare caratteri da 1 a 20
      String regex = "[a-zA-Z]{1,20}";
      Scanner sc = new Scanner(System.in);
      System.out.println("Inserisci il nome dello studente:");
      String name = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(name);
      if(m.matches()) {
         System.out.println("Il nome è appropriato");
      } else {
         System.out.println("Il nome è inappropriato");
      }
   }
}

Output 1

Inserisci il nome dello studente:
Mouktika
Il nome è appropriato

Output 2

Inserisci il nome dello studente:
ka 34
Il nome è inappropriato

Output 3

Inserisci il nome dello studente:
Sri Veera Venkata Satya Sai Suresh Santosh Samrat
Il nome è inappropriato
Ti potrebbe interessare