Java里的matchers方法,Java中正则表达式Matcher的useTransparentBounds方法

背景

最近在看《两周自制脚本语言》,里面的词法分析部分使用的是正则表达式来匹配

看到它里面使用了一个没见过的方法useTransparentBounds,快速查了下文档发现不好理解,于是决定记录下来

文档

先放下文档:

Sets the transparency of region bounds for this matcher.

Invoking this method with an argument of true will set this matcher to use transparent bounds. If the boolean argument is false, then opaque bounds will be used.

Using transparent bounds, the boundaries of this matcher's region are transparent to lookahead, lookbehind, and boundary matching constructs. Those constructs can see beyond the boundaries of the region to see if a match is appropriate.

Using opaque bounds, the boundaries of this matcher's region are opaque to lookahead, lookbehind, and boundary matching constructs that may try to see beyond them. Those constructs cannot look past the boundaries so they will fail to match anything outside of the region.

By default, a matcher uses opaque bounds.

Parameters:

b - a boolean indicating whether to use opaque or transparent regions

从方法名中可以看出意思是 "使用透明边界",从文档中也可以看出默认使用不透明边界,而理解的难点就在 “边界” 一词,下面说下我的理解

什么是边界

采用不透明边界的效果

public class Test {

public static void main(String argv[]) {

String regex="\\b123\\b";

String text = "test123 test";

Matcher matcher = Pattern.compile(regex).matcher(text);

// 默认采用不透明边界

// matcher.useTransparentBounds(true);

matcher.region(4,text.length());

matcher.find();

System.out.println("index : "+matcher.start());

// index : 4

}

}

采用透明边界的效果

public class Test {

public static void main(String argv[]) {

String regex="\\b123\\b";

String text = "test123 test";

Matcher matcher = Pattern.compile(regex).matcher(text);

matcher.useTransparentBounds(true);

matcher.region(4,text.length());

matcher.find();

System.out.println("index : "+matcher.start());

// 报 No match available 错

}

}

边界

关键点是使用了region方法来限定被匹配字符串的范围,它使得模式串是从 被匹配串text 的中间开始匹配,如下:

d23a193c22d4e33d413d12f757183ff2.png

我认为 “边界” 指的就是这条红线,它是相对模式串regex而言的

我们知道regex内容是 \\b123\\b,指的是匹配123且两边为单词边界\b

对于regex而言,如果这条红线是不透明的,相当于一面墙,那么它就会认为已经到达了边界即成功匹配\b,匹配完123后自然也有一个单词边界,于是匹配成功

假如这条红线是透明,regex就看得见前面的字符串,它就会知道前面还有字符串,没有到达单词边界,于是匹配失败

以上就是我对useTransparentBound中边界的理解

作者: auko

文章链接: 版权链接占位

版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 3.0 许可协议。转载请注明出处!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值