Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Character Class Subtraction ใน Java Regular Expressions

สามารถลบช่วง (range) หนึ่งออกจากอีกช่วงหนึ่งได้ ใช้ character class 2 แบบ: negation (^) และ intersection (&&)

เช่น intersection ของ [a-l] และ [^e-h] จะได้ตัวอักษร a ถึง l ลบตัวอักษร e-h ออก

ตัวอย่าง

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 = "[a-l&&[^e-h]]";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
            System.out.print(matcher.group() + " ");
        }
        System.out.println("Number of matched characters: " + count);
    }
}

ผลลัพธ์

Enter input text: abcdefghijklmnopq
a b c d i j k l
Number of matched characters: 8