使用Java中的正则表达式匹配字符串中的元音的程序
您可以将所有必需的字符分组,以在方括号“[]”内进行匹配,即,元字符/子表达式“[]”与所有指定的字符匹配。因此,要匹配所有字母,请在其中指定元音字母,如下所示-
[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("Enter input string: ");
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("The input string contains vowels");
} else {
System.out.println("The input string does not contain vowels");
}
}
}输出结果
Enter input string: hello how are you welcome The input string contains vowels
例子2
import java.util.Scanner;
public class Test {
public static void main( String args[] ) {
String regex = "[aeiouAEIOU]";
System.out.println("Enter input string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean result = input.matches(regex);
if(result) {
System.out.println("The input string contains vowels");
} else {
System.out.println("The input string does not contain vowels");
}
}
}输出结果
Enter input string: hello how are you welcome The input string does not contain vowels
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志