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


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]";
      //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 of non-vowel characters : "+count);
   }
}

输出

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

更新时间:2020 年 1 月 13 日

3K+ 浏览次数

开启你的职业生涯

完成课程获得证书

开始
广告
© . All rights reserved.