字符类: 范围 - 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.