解釋 Java 正則表示式中的子表示式 "[...]"


子表示式 “[...]” 匹配方括號中指定的任何單個字元。

示例 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SpecifiedCharacters {
   public static void main( String args[] ) {
      String regex = "[hwt]";
      String input = "Hi how are you welcome to Tutorialspoint";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}

輸出

Number of matches: 6

示例 2

以下 Java 程式接受使用者輸入的 5 個字串,並列印包含母音字母的字串/單詞。

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "^.*[aeiou].*$";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter 5 input strings: ");
      String input[] = new String[5];
      for (int i=0; i<5; i++) {
         input[i] = sc.nextLine();
      }
      //Creating a Pattern object
      Pattern p = Pattern.compile(regex);
      System.out.println("strings that contain vowel letters: ");
      for(int i=0; i<5;i++) {
         //Creating a Matcher object
         Matcher m = p.matcher(input[i]);
         if(m.matches()) {
            System.out.println(m.group());
         }
      }
   }
}

輸出

Enter 5 input strings:
hello
sample
rhythm
cry
gym
strings that contain vowel letters:
hello
sample

更新於: 19-11-2019

287 次檢視

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告