要创建由两个或多个单独的字符类组成的单个字符类,请使用并集。要创建并集,只需将一个类嵌套在另一个类中,例如[1-3[5-7]]。
package org.nhooo.example.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class CharacterClassUnionDemo { public static void main(String[] args) { // 定义与数字1,2,3,5,6,7匹配的正则表达式 String regex = "[1-3[5-7]]"; String input = "1234567890"; // 将给定的正则表达式编译为模式。 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 "1" found at 0 to 1. Text "2" found at 1 to 2. Text "3" found at 2 to 3. Text "5" found at 4 to 5. Text "6" found at 5 to 6. Text "7" found at 6 to 7.