Java如何编写范围字符类正则表达式?

要定义包含一定范围值的字符类,请将-元字符放在要匹配的第一个字符和最后一个字符之间。例如[a-e]。您也可以像这样指定多个范围[a-zA-Z]。这将匹配从a到z(小写)或A到Z(大写)的所有字母。

在下面的示例中,我们匹配bat以一个数字开头和结尾的单词,该单词的取值范围为从3到7。

package org.nhooo.example.regex;

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

public class CharacterClassesRangeClassDemo {
    public static void main(String[] args) {
        // 定义将搜索所有字符串序列的正则表达式
        // 以蝙蝠和数字开头的数字[3-7]
        String regex = "bat[3-7]";
        String input =
            "bat1, bat2, bat3, bat4, bat5, bat6, bat7, bat8";

        // 将给定的正则表达式编译为模式。
        Pattern pattern = Pattern.compile(regex);

        // 创建将匹配给定输入的匹配器
        // 反对这种模式。
        Matcher matcher = pattern.matcher(input);

        // 找到所有匹配项并打印出来。
        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                matcher.group(), matcher.start(),
                matcher.end());
        }
    }
}

该程序将从输入中匹配以下字符串:

Text "bat3" found at 12 to 16.
Text "bat4" found at 18 to 22.
Text "bat5" found at 24 to 28.
Text "bat6" found at 30 to 34.
Text "bat7" found at 36 to 40.