正则表达式之零宽断言

正则表达式之零宽断言

用于查找在某些内容(但并不包括这些内容)之前或之后的东西

  1. 零宽度正预测先行断言 - (?=exp)

    匹配exp前面的位置

     正则表达式:.+(?=://)
     原始字符串:http://localhost:8080/awesome-god?love=1000&believe=true
     得到的结果:http
    
  2. 零宽度正回顾后发断言 - (?<=exp)

    匹配exp后面的位置

     正则表达式:(?<=\?).+
     原始字符串:http://localhost:8080/awesome-god?love=1000&believe=true
     得到的结果:love=100&believe=true
    
  3. 零宽度负预测先行断言 - (?!exp)

    匹配后面跟的不是exp的位置

     正则表达式:\d{4}(?!&)
     原始字符串:http://localhost:8080/awesome-god?love=1000&believe=true
     得到的结果:8080
    
  4. 零宽度负回顾后发断言 - (?<!exp)

    匹配前面不是exp的位置

     正则表达式:(?<!=)\d{4}
     原始字符串:http://localhost:8080/awesome-god?love=1000&believe=true
     得到的结果:8080
    

附Java测试代码:

  1. 完整代码

     import java.util.Arrays;
     import java.util.LinkedList;
     import java.util.List;
     import java.util.regex.Matcher;
     import java.util.regex.Pattern;
    
     /**
      * Some tools for Regex
      */
     public class RegexUtils {
    
     	/**
     	 * 根据正则表达式提取字符串
     	 * [@param](https://my.oschina.net/u/2303379) str
     	 * [@param](https://my.oschina.net/u/2303379) regex
     	 * [@return](https://my.oschina.net/u/556800)
     	 */
     	public static String[] find(String str, String regex) {
     		if (isEmpty(str)) {
     			return new String[0];
     		}
     		Pattern pattern = Pattern.compile(regex);
     		Matcher matcher = pattern.matcher(str);
     		List<String> list = new LinkedList<>();
     		while(matcher.find()) {
     			list.add(matcher.group());
     		}
     		return list.toArray(new String[list.size()]);
     	}
    
     	public static void main(String[] args) {
     		String[] array;
     		String str = "http://localhost:8080/awesome-god?love=1000&believe=true";
    
     		array = find(str, ".+(?=://)");
     		System.out.println("1. 零宽度正预测先行断言 - (?=exp): " + Arrays.toString(array));
    
     		array = find(str, "(?<=\\?).+");
     		System.out.println("2. 零宽度正回顾后发断言 - (?<=exp): " + Arrays.toString(array));
    
     		array = find(str, "\\d{4}(?!&)");
     		System.out.println("3. 零宽度负预测先行断言 - (?!exp): " + Arrays.toString(array));
    
     		array = find(str, "(?<!=)\\d{4}");
     		System.out.println("4. 零宽度负回顾后发断言 - (?<!exp): " + Arrays.toString(array));
     	}
     }
    
  2. 输出结果

     1. 零宽度正预测先行断言 - (?=exp): [http]
     2. 零宽度正回顾后发断言 - (?<=exp): [love=1000&believe=true]
     3. 零宽度负预测先行断言 - (?!exp): [8080]
     4. 零宽度负回顾后发断言 - (?<!exp): [8080]
    

参考文档:正则表达式之零宽断言

猜你喜欢

转载自my.oschina.net/u/3251146/blog/2878103