使用零宽度断言负前瞻来匹配包含字符串“abc”的字符串
大家好: 我正在尝试使用零宽度断言负前瞻来匹配包含字符串“abc”的字符串,这就是我得到的:
Pattern pattern = new Perl5Compiler().compile("((?!abc).)+");
Perl5Matcher matcher = new Perl5Matcher();
System.out.println(matcher.matches("abc", pattern));
System.out.println(matcher.matches("abdas dfas", pattern));
System.out.println(matcher.matches("d abc ", pattern));
System.out.println(matcher.matches("fafabcdef", pattern));
结果是:
false
true
false
false
我不明白的是为什么字符串“abc”不包含t 匹配,它在断言“abc”之后不包含任何字符。谁能弄清楚这是如何工作的吗?谢啦~
Hi all:
I'm trying using zero-width assertions negative lookahead to match a string that does's contains string "abc",and this is what I got:
Pattern pattern = new Perl5Compiler().compile("((?!abc).)+");
Perl5Matcher matcher = new Perl5Matcher();
System.out.println(matcher.matches("abc", pattern));
System.out.println(matcher.matches("abdas dfas", pattern));
System.out.println(matcher.matches("d abc ", pattern));
System.out.println(matcher.matches("fafabcdef", pattern));
and the result is:
false
true
false
false
What I can't understand is why the string "abc" doesn't matches, it doesn't contains any character after the assertion "abc". Can anyone please figure out how this works? tks~
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
环顾四周开始在位置上做事,而不是在角色上。因此,对于字符串
"abc"
,正则表达式的这一部分:(?!abc).
开始向前查看位置 在字符串中的“a”
之前。该位置是“a”
之前的空字符串。这就是它无法匹配的原因。Look-arounds start doing their thing on positions, not on characters. So, with the string
"abc"
, this part of your regex:(?!abc).
starts looking ahead on the position before the"a"
in your string. The position is the empty string before"a"
. That's why it fails to match.嗯,这与 Perl5 的实际工作方式不同。
它必须具有隐式 ^ 和 \z。
那些不匹配的,因为有一些位置匹配/abc/。
Hum, that differs from how Perl5 actually works.
It must have an implicit ^ and \z.
The ones that don't match because there some position that matches /abc/.