字元類: 範圍 - Java 正則表示式


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

字元類的範圍變體允許你使用字元範圍,即表示式 [a-z] 匹配字母 a 到 z 之間的單個字元,而表示式 [^A-Z] 匹配的字元不是大寫字母。

示例 1

 動態演示

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]";
      //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 range (a-z): "+count);
   }
}

輸出

Enter input text:
sample data 5423 #@ %*&
Number characters from the range (a-z): 10

示例 2

 動態演示

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample3 {
   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]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      if (matcher.find()) {
         System.out.println("match occurred");
      } else {
         System.out.println("match not occurred");
      }
   }
}

輸出 1

Enter input text:
sample data
match occurred

輸出 2

Enter input text:
SAMPLEDATA
match not occurred

更新於: 13-Jan-2020

105 瀏覽

귀하의 경력을 시작하세요

과정을 완료하여 자격증을 취득하세요

시작하기
광고
© . All rights reserved.