字元類:相交 - Java 正則表示式


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

字元類的相交變體允許你匹配在具有相交關係的範圍中常見的字元。

使用 && 定義範圍之間的相交關係,即表示式 [a-z&&[r-u]] 匹配 r 到 u 的單個字元。

示例

 線上演示

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&&[r-u]]";
      //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 of matched characters: "+count);
   }
}

輸出

Enter input text:
how are you welcome to tutorialspoint
Number of matched characters: 9

更新於: 10-Jan-2020

247 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

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