字符类:联合 - Java 正则表达式

javaobject oriented programmingprogramming更新于 2025/2/13 21:00:17

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("输入文本:");
      String input = sc.nextLine();
      String regex = "[a-z[0-9]]";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      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);
   }
>

输出

输入文本:
示例数据 12345
Number characters from the ranges (a-z or 0-9): 11

相关文章


有用资源