Java如何编写字符类交集正则表达式?
您可以使用&&运算符来组合定义一组字符的类。它只会匹配两个类的通用字符(交集)。
package org.nhooo.example.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharacterClassIntersectionDemo {
public static void main(String[] args) {
//定义正则表达式将搜索从“a”到“z”的字符
//并且是'c'或'a'或't'字符。
String regex = "[a-z&&[cat]]";
//将给定的正则表达式编译为模式。
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(
"The quick brown fox jumps over the lazy dog");
//查找每个匹配并打印
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(), matcher.end());
}
}
}该程序将显示以下结果:
Text "c" found at 7 to 8. Text "t" found at 31 to 32. Text "a" found at 36 to 37.
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短