字元類:減法 - Java 正則表示式


您可以將一個範圍從另一個範圍內減去並將其用作新範圍。您可以透過使用兩種字元類變數(即否定和交集)來實現此目的。

例如,範圍 [a-l] 和 [^e-h] 的交集提供給您字元 a 到 l,即減去字元 [e-h] 的範圍

示例

 即時演示

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-l&&[^e-h]]";
      //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.print(matcher.group()+" ");
      }
      System.out.println("Number of matched characters: "+count);
   }
}

輸出

Enter input text:
abcdefghijklmnopq
a b c d i j k l Number of matched characters: 8

更新日期:2020 年 1 月 10 日

398 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.