English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Espressione secondaria/simbolo " re {n, m} Corrispondenze di almeno n e massimo m con l'espressione precedente.
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
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"); } } }
Inserisci il nome dello studente: Mouktika Il nome è appropriato
Inserisci il nome dello studente: ka 34 Il nome è inappropriato
Inserisci il nome dello studente: Sri Veera Venkata Satya Sai Suresh Santosh Samrat Il nome è inappropriato