使用 Java 中的正则表达式匹配字符串中元音的程序
javaobject oriented programmingprogramming更新于 2024/5/11 5:00:17
您可以将所有需要匹配的字符分组到方括号"[ ]"中,即元字符/子表达式"[ ]"匹配所有指定的字符。因此,要匹配所有字母,请指定这些字母中的元音字母,如下所示 −
[aeiouAEIOU]
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchVowels {
public static void main( String args[] ) {
String regex = "[aeiouAEIOU]";
System.out.println("输入输入字符串: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//编译正则表达式
Pattern.compile(regex);
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("输入字符串包含元音");
} else {
System.out.println("输入字符串不包含元音");
}
}
}
输出
输入输入字符串: hello how are you welcome 输入的字符串包含元音
示例 2
import java.util.Scanner;
public class Test {
public static void main( String args[] ) {
String regex = "[aeiouAEIOU]";
System.out.println("输入输入字符串: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean result = input.matches(regex);
if(result) {
System.out.println("输入的字符串包含元音");
} else {
System.out.println("输入的字符串不包含元音");
}
}
}
输出
输入输入字符串: hello how are you welcome 输入的字符串不包含元音
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

