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.
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特