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 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短