在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();
      //Compiling the regular expression
      Pattern.compile(regex);
      //Compiling the regular expression
      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

更新於: 2019 年 11 月 21 日

4K+ 次觀看

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.