Lookaheads
是一种模式,它告诉JavaScript在字符串中向前看以进一步检查模式。当您想要在同一个字符串上搜索多个模式时,这非常有用。有两种lookaheads
: positive lookahead
和negative lookahead
。一个positive lookahead
向前看将确保搜索模式中的元素存在,但实际上不匹配它。正向前瞻用作(?=...)
,其中...
是不匹配的必需部分。另一方面, negative lookahead
将确保搜索模式中的元素不存在。负向前瞻用作(?!...)
,其中...
是您不希望在那里的模式。如果不存在负前瞻部分,则返回模式的其余部分。前瞻有点令人困惑,但一些例子会有所帮助。 让quit =“qu”;
让noquit =“qt”;
让quRegex = / q(?= u)/;
让qRegex = / q(?!u)/;
quit.match(quRegex); //返回[“q”]
noquit.match(qRegex); //返回[“q”]
lookaheads
更实际用途是检查一个字符串中的两个或更多个模式。这是一个(天真)简单的密码检查器,可以查找3到6个字符和至少一个数字: let password =“abc123”;
让checkPass = /(?= \ w {3,6})(?= \ D * \ d)/;
checkPass.test(密码); //返回true
lookaheads
在pwRegex
匹配长的时间大于5个字符,并有两个连续的数字密码。 lookaheads
。
testString: 'assert(pwRegex.source.match(/\(\?=.*?\)\(\?=.*?\)/) !== null, "Your regex should use two positive lookaheads
.");'
- text: 你的正则表达式不应该匹配"astronaut"
testString: 'assert(!pwRegex.test("astronaut"), "Your regex should not match "astronaut"
");'
- text: 你的正则表达式不应该与"airplanes"
匹配
testString: 'assert(!pwRegex.test("airplanes"), "Your regex should not match "airplanes"
");'
- text: 你的正则表达式不应该匹配"banan1"
testString: 'assert(!pwRegex.test("banan1"), "Your regex should not match "banan1"
");'
- text: 你的正则表达式应该匹配"bana12"
testString: 'assert(pwRegex.test("bana12"), "Your regex should match "bana12"
");'
- text: 你的正则表达式应该匹配"abc123"
testString: 'assert(pwRegex.test("abc123"), "Your regex should match "abc123"
");'
- text: 你的正则表达式不应该匹配"123"
testString: 'assert(!pwRegex.test("123"), "Your regex should not match "123"
");'
- text: 你的正则表达式不应该匹配"1234"
testString: 'assert(!pwRegex.test("1234"), "Your regex should not match "1234"
");'
```