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 38节贺卡简短祝福语
15 新疆新年祝福语大全简短
16 近代生日祝福语简短精辟
17 发廊元旦祝福语大全简短
18 初八祝福语简短语