从一组字符中进行匹配的 Java 正则表达式

javaobject oriented programmingprogramming更新于 2025/2/12 6:36:17

Java 正则表达式中的字符类使用方括号"[ ]"定义,该字符类匹配指定的或可能的字符集中的单个字符。

例如,正则表达式 [abc] 匹配单个字符 a 或 b 或 c。类似地,"[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("输入输入文本: ");
      String input = sc.nextLine();
      String regex = "[a-z]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("从 a 到 z 的字符数:"+count);
   }
}

输出

输入输入文本:
示例数据 1234$
从 a 到 z 的字符数:10

示例 2

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]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("非字母字符数:"+count);
   }
}

输出

输入输入文本:
sample data 1234
非字母字符数:7

相关文章


有用资源