字元型別:並集 - Java 正則表示式


Java 正則表示式中的字元型別使用方括號“[]”定義,此子表示式匹配指定的一組可能字元中的一個字元。例如,正則表示式 [abc] 匹配單個字元 a、b 或 c。

字元型別的並集變數允許您從指定範圍中的某個字元進行匹配,即表示式 [a-z[0-9]] 匹配的單個字元可能是一個小寫字母 (a-z) 或一個數字 (0-9)。

示例

 線上演示

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample1 {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[a-z[0-9]]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number characters from the ranges (a-z or 0-9): "+count);
   }
}

輸出

Enter input text:
sample DATA 12345
Number characters from the ranges (a-z or 0-9): 11

更新於:13-Jan-2020

493次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.