Java如何编写字符类减法正则表达式?

您可以使用减法来否定一个或多个嵌套字符类。本示例创建一个单个字符类,该字符类匹配从a到z的所有字符,元音除外(“ a”,“ i”,“ u”,“ e”,“ o”)。可以用减法写为[a-z&&[^aiueo]]。

package org.nhooo.example.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CharacterClassSubtractionDemo {
    public static void main(String[] args) {
        // 定义正则表达式将搜索从“ a”到“ z”的字符
        // 和不包括元音。
        String regex = "[a-z&&[^aiueo]]";

        // 将给定的正则表达式编译为模式,然后
        // 创建一个匹配器,将匹配给定的输入
        // 这种模式。
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher("The quick brown fox.");

        // 查找每个匹配并打印
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                matcher.group(), matcher.start(), matcher.end());
        }
    }
}

这是程序的结果:

Text "h" found at 1 to 2.
Text "q" found at 4 to 5.
Text "c" found at 7 to 8.
Text "k" found at 8 to 9.
Text "b" found at 10 to 11.
Text "r" found at 11 to 12.
Text "w" found at 13 to 14.
Text "n" found at 14 to 15.
Text "f" found at 16 to 17.
Text "x" found at 18 to 19.