English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Espressione regolare/Carattere speciale " \ d corrisponde ai numeri.
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 = "Questo è un testo di esempio 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("Numero di corrispondenze: " + count); } }
Risultato dell'output
Numero di corrispondenze: 2
Ecco un programma Java che legge 10 cifre dall'utente.
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("Inserisci il tuo numero di telefono (10 cifre): "); String input = sc.nextLine(); // Creare un oggetto Pattern Pattern p = Pattern.compile(regex); // Creare un oggetto Matcher Matcher m = p.matcher(input); if(m.find()) { System.out.println("OK"); } else { System.out.println("Input errato"); } } }
Inserisci il tuo numero di telefono (10 cifre): 9848022338 OK
Inserisci il tuo numero di telefono (10 cifre): 545 Input errato