English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Di seguito è riportata l'espressione regolare per abbinare le lettere nel input fornito - Note di esperienza
"^[a-zA-Z]*$"
Dove,
^ abbinamento all'inizio della frase.
[a-zA-z] abbinamento lettere minuscole e maiuscole.
* rappresenta zero o più volte.
& rappresenta la fine della riga.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ContainsAlphabetExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String names[] = new String[5]; for (int i = 0; i < names.length; i++) { System.out.println("Inserisci il tuo nome: "); names[i] = sc.nextLine(); } // espressione regolare accettata per lettere inglesi String regex = "^[a-zA-Z]*$"; // creare un oggetto Pattern Pattern pattern = Pattern.compile(regex); for (String name : names) { // creare un oggetto Matcher Matcher matcher = pattern.matcher(name); if(matcher.matches()) { System.out.println(name+" "+"is "+"a "+"valid "+"name"); } else { System.out.println(name+" è un nome non valido"); } } } }
Risultato dell'output
Inserisci il tuo nome: krishna Inserisci il tuo nome: kasyap Inserisci il tuo nome: maruthi# Inserisci il tuo nome: Sai_Ram Inserisci il tuo nome: Vani.Viswanath krishna è un nome valido kasyap è un nome valido maruthi# non è un nome valido Sai_Ram non è un nome valido Vani.Viswanath non è un nome valido
import java.util.Scanner; public class Just { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Inserisci il tuo nome: "); String name = sc.nextLine(); String regex = "^[a-zA-Z]*$"; boolean result = name.matches(regex); if(result) { System.out.println("Il nome fornito è valido"); } else { System.out.println("Il nome fornito non è valido"); } } }
Risultato dell'output
Inserisci il tuo nome: vasu#dev Il nome fornito non è valido