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 老师祝福语简短100字
16 叔叔生日祝福语简短励志
17 送情侣生日祝福语简短
18 许愿星姐妹祝福语简短