Java如何编写字符类减法正则表达式?
您可以使用减法来否定一个或多个嵌套字符类。本示例创建一个单个字符类,该字符类匹配从a到z的所有字符,元音除外(“a”,“i”,“u”,“e”,“o”)。可以用减法写为[a-z&&[^aiueo]]。
package org.nhooo.example.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharacterClassSubtractionDemo {
public static void main(String[] args) {
//定义正则表达式将搜索从“a”到“z”的字符
//和不包括元音。
String regex = "[a-z&&[^aiueo]]";
//将给定的正则表达式编译为模式,然后
//创建一个匹配器,将匹配给定的输入
//这种模式。
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("The quick brown fox.");
//查找每个匹配并打印
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(), matcher.end());
}
}
}这是程序的结果:
Text "h" found at 1 to 2. Text "q" found at 4 to 5. Text "c" found at 7 to 8. Text "k" found at 8 to 9. Text "b" found at 10 to 11. Text "r" found at 11 to 12. Text "w" found at 13 to 14. Text "n" found at 14 to 15. Text "f" found at 16 to 17. Text "x" found at 18 to 19.
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西