为什么连续的前瞻并不总是有效 [英] Why consecutive lookaheads do not always work

查看:80
本文介绍了为什么连续的前瞻并不总是有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个正则表达式,当至少有5个字符和2个数字时返回true。为此,我使用了前瞻(即(?= ...))。

I want a regex which returns true when there is at least 5 characters et 2 digits. For that, I use a the lookahead (i. e. (?=...)).

// this one works
let pwRegex = /(?=.{5,})(?=\D*\d{2})/;
let result = pwRegex.test("bana12");

console.log("result", result) // true

// this one won't
pwRegex = /(?=.{5,})(?=\d{2})/;
result = pwRegex.test("bana12");

console.log("result", result) // false

为什么我们需要添加 \ D * 才能使其正常工作?

Why we need to add \D* to make it work ?

对我来说, \d {2} \ D * \d {2} <宽松/ code>所以它不应该允许接受测试?

For me, \d{2} is looser than \D*\d{2} so it should not allow an acceptance of the test?

推荐答案

你的前瞻只测试当前的匹配位置。由于你不匹配任何东西,这意味着从一开始。由于 bana12 不以两位数字开头,因此 \d {2} 失败。它就这么简单;)

Your lookaheads only test from the current match position. Since you don't match anything, this means from the start. Since bana12 doesn't start with two digits, \d{2} fails. Its as simple as that ;)

另外,请注意, \d {2} 表示你的数字有相邻。这是你的意图吗?

Also, note that having \d{2} means your digits has to be adjacent. Is that your intention?

要简单地要求2位数,不需要相邻,请尝试

To simply require 2 digits, that doesn't need to be adjacent, try

/(?=.{5,})(?=\D*\d\D*\d)/

这篇关于为什么连续的前瞻并不总是有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆