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.
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西