Regex 锚点,环视

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

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

 

/**
 * 环视使用
 * */
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:逆序环视结构中的子表达式完全没有限制。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值