Java如何编写否定字符类正则表达式?
否定类是从^元字符开始的字符类,该元字符将排除在方括号内的一组已定义字符。例如,以下示例中的否定类h[^ao]t仅匹配单词,hit而排除单词hat和hot。
package org.nhooo.example.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharacterClassesNegationClassDemo {
public static void main(String[] args) {
//定义一个正则表达式,它将搜索所有
//以“h”开头和以“t”结尾的字符串序列
//并有一个中间字母,但出现在中间的字母除外
//方括号内^字符的右边
//(“a”和“o”)
String regex = "h[^ao]t";
//编译模式并获得匹配对象。
Pattern pattern = Pattern.compile(regex);
Matcher matcher =
pattern.matcher("Wow, that hot hat will make a hit");
//找到所有匹配项并打印出来。
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d.%n",
matcher.group(), matcher.start(), matcher.end());
}
}
}程序输出以下结果:
Text "hit" found at 30 to 33.
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短