字元類:否定 - 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP