Java 正则表达式用于检查字符串是否包含字母
以下是用正则表达式在给定输入中匹配字母-
"^[a-zA-Z]*$"
其中,
- ^ 匹配句子的开头。
- [a-zA-z] 匹配小写字母和大写字母。
- * 表示可出现 0 次或多次。
- & 表示行的结尾。
示例 1
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(); } //Regular expression to accept English alphabet String regex = "^[a-zA-Z]*$"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); for (String name : names) { //Creating a Matcher object 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
示例 2
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
广告