---
title: "Regex 锚点，环视"
author: "roway"
date: "2012-11-01T14:10:00Z"
tags: []
categories: ["编程语言"]
slug: "regex"
draft: false
lastmod: "2012-11-13T13:50:21Z"
id: 1722884
url: "https://roway.iteye.com/blog/1722884"
---

1.锚点------不会匹配任何具体的字符，而只能匹配特定的位置。(边界匹配器)  
作用：规定匹配的位置  
形式：\\b单词分界符锚点  
功能是：在\\b的一侧出现单词字符，在\\b的另一侧不出现单词字符  
2.单词分界符注意事项  
a.\\b表示单词分界符，要求一侧是单词字符，另一侧是非单词字符。  
b.单词字符通常是指的是英文字符、数字字符，对中文不适用  
c.非单词字符通常指的是各种标点符号和空白字符。  
3.^------匹配一行的开头(有可能变化)------标准情况等价于\\A  
$------匹配一行的末尾(有可能变化)------标准情况等价于\\Z  
\\A-----匹配整个字符串的开头  
\\z-----匹配整个字符串的末尾  
4.环视  
a.锚点对位置的判断不够灵活。  
b.作用：应用子表达式对位置进行判断。  
c.形式：形式(...代表子表达式) 名称 匹配意义  
(?=...)------ 肯定顺序环视 右侧文本能由子表达式匹配  
(?!...)------ 否定顺序环视 右侧文本不能由子表达式匹配  
(?&lt;=...)------ 肯定逆序环视 左侧文本能由子表达式匹配

(?&lt;!...)----- 否定逆序环视 左侧文本不能由子表达式匹配。

 

```
/**
 * 环视使用
 * */
public class LookAheadBasic {

	public static void main(String[] args) {

		String[] strings = new String[] { "Jeff", "Jeffrey", "Jefferson" };

		String[] regexes = new String[] { "Jeff", "Jeff(?=rey)", "Jeff(?!rey)" };

		for (String regex : regexes) {
			for (String str : strings) {
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(str);
				if (m.find()) {
					System.out.println("\"" + str
							+ "\" can be matched with regex \"" + regex + "\"");
				} else {
					System.out.println("\"" + str
							+ "\" can not be matched with regex \"" + regex
							+ "\"");
				}
			}
			System.out.println("");
		}

	}

}
```

 

```
/**
 * 环视的使用
 * */
public class LookBehindBasic {
	
	public static void main(String[] args) {

		String[] strings = new String[] {"see", "bee", "tee"};

		String[] regexes = new String[] { "(?<=s)ee", "(?<!s)ee"};

		for (String regex : regexes) {
			for (String str : strings) {
				Pattern p = Pattern.compile(regex);
				Matcher m = p.matcher(str);
				if(m.find()) {
					System.out.println("\"" + str
							+ "\" can be matched with regex \"" + regex
							+ "\"");
				}
				else {
					System.out.println("\"" + str
							+ "\" can not be matched with regex \"" + regex
							+ "\"");
				}
			}
			System.out.println("");
		}

	}

}
```

 

```
/**
 * 给数值字符串插入","格式化数值字符串
 * */
public class LookAroundReplace {

	public static void main(String[] args) {
		String[] numbers = new String[] { "123456", "1234567890" };

		String regex = "(?<=\\d)(?=(\\d{3})+(?!\\d))";

		for (String number : numbers) {
			System.out.println("Before processing:\t" + number);
			System.out.println("After processing:\t"
					+ number.replaceAll(regex, ","));
		}

	}

}
```

 

 

5.环视的注意事项  
a.环视结构仅用于布尔判断(返回真/假)，结构内的子表达式所匹配的文本，不会保存在整个表达式的匹配结果之中。  
b.逆序环视结构对子表达式存在限制。  
6.逆序环视结构的限制  
a.Perl,Python:逆序环视结构中的子表达式必须固定长度  
b.PHP，Java:逆序环视结构中的子表达式可以不定长度，但必须有上限。  
c..NET:逆序环视结构中的子表达式完全没有限制。