前提
今天做正则的时候看到这个?!比较迷惑,印象中正则好像这有感叹号,于是查了下资料,发现还是自己的知识太过于单薄了,于是打算记录一下。吐槽一下,这个术语实在有些绕口和难懂,也不知道是谁想出来的。定义就不说了,实在难懂,一般有四种零宽度断言。
- ?=exp (匹配以exp表达式结尾)
- ?<=exp (匹配以exp表达式开头)
- ?!exp (匹配不以exp表达式结尾)
- ?<!exp (匹配不以exp表达式开头)
ex1: ?=exp
//匹配danc前面的字符串
final String regex = "(.+)(?=danc)";
final String str = "I'm singing while you're dancing";
System.out.println(str.matches(regex));
Matcher matcher = Pattern.compile(regex).matcher(str);
while(matcher.find()) {
System.out.println(matcher.group());
}
ex2: ?<=exp
//匹配danc后面的字符串
final String regex = "(?<=danc)(.+)";
final String str = "I'm singing while you're dancing";
System.out.println(str.matches(regex));
Matcher matcher = Pattern.compile(regex).matcher(str);
while(matcher.find()) {
System.out.println(matcher.group());
}
ex3: ?!exp
//匹配后面不带空格的字符串
final String regex = "([\\w\\']+)(?!\\s+)";
final String str = "I'm singing while you're dancing";
System.out.println(str.matches(regex));
Matcher matcher = Pattern.compile(regex).matcher(str);
while(matcher.find()) {
System.out.println(matcher.group());
}
ex4: ?<!exp
//匹配不以空格开头的字符串
final String regex = "(?<!\\s)([\\w\\']+)";
final String str = "I'm singing while you're dancing";
System.out.println(str.matches(regex));
Matcher matcher = Pattern.compile(regex).matcher(str);
while(matcher.find()) {
System.out.println(matcher.group());
}