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 爱生日祝福语简短独特