以下是匹配给定输入中的字母的正则表达式-
"^[a-zA-Z]*$"
哪里,
^匹配句子的开头。
[a-zA-z]匹配小写字母和大写字母。
*表示零次或多次。
&表示行尾。
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("Enter your name: "); names[i] = sc.nextLine(); } //接受英文字母的正则表达式 String regex = "^[a-zA-Z]*$"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); for (String name : names) { //创建一个Matcher对象 Matcher matcher = pattern.matcher(name); if(matcher.matches()) { System.out.println(name+" is a valid name"); } else { System.out.println(name+" is not a valid name"); } } } }
输出结果
Enter your name: krishna Enter your name: kasyap Enter your name: maruthi# Enter your name: Sai_Ram Enter your name: Vani.Viswanath krishna is a valid name kasyap is a valid name maruthi# is not a valid name Sai_Ram is not a valid name Vani.Viswanath is not a valid name
import java.util.Scanner; public class Just { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.nextLine(); String regex = "^[a-zA-Z]*$"; boolean result = name.matches(regex); if(result) { System.out.println("Given name is valid"); } else { System.out.println("Given name is not valid"); } } }
输出结果
Enter your name: vasu#dev Given name is not valid