字符类:否定 - Java 正则表达式

javaobject oriented programmingprogramming更新于 2025/2/13 19:56:17

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

例如,正则表达式 [abc] 匹配单个字符 a 或 b 或 c。类似地,"[a-z]"匹配从 a 到 z 的单个字符。

类似地,字符类的否定变体定义为"[^ ]"(方括号内有 ^),它匹配不在指定的或可能字符集中的单个字符。

例如,正则表达式 [^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("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[^aeiou]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number of non-vowel characters : "+count);
   }
}

输出

Enter input text:
sample data
Number of non-vowel characters : 7

相关文章


有用资源