Java如何编写联合字符类正则表达式?
要创建由两个或多个单独的字符类组成的单个字符类,请使用并集。要创建并集,只需将一个类嵌套在另一个类中,例如[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.
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短