正则表达式匹配长度超过 5 个字符且有两个连续数字的密码 [英] regex to match passwords that are greater than 5 characters long and have two consecutive digits
问题描述
这就是我所拥有的,有人可以告诉我我错在哪里吗?
Here's what I have, can someone please tell me where I am wrong?
let sampleWord = "bana12";
let pwRegex = /(?=\w{5})(?=\d{2,})/; // Change this line
let result = pwRegex.test(sampleWord);
console.log(result);
它适用于仅包含字母或仅包含数字的密码,但不适用于两者.
It works for passwords that contain only letters or only numbers, but not for both.
推荐答案
在 \d{2}
之前使用 .*
因为连续的数字可能出现在字符串的任何位置.您当前的正则表达式应该首先检查是否存在两位数字.
Use .*
before \d{2}
since the consecutive digits may occur anywhere in the string. Your current regex should check for two digits to be present at very first.
let sampleWord = "bana12";
let pwRegex = /^(?=\w{5})(?=.*\d{2,})/; // Change this line
console.log( pwRegex.test(sampleWord))
请注意, \w
仅匹配单词字符,因此如果输入字符串包含 5 个非单词字符,则您的正则表达式将失败.所以为了检查字符串长度,最好使用.
而不是\w
.
Note that \w
matches only the word characters, so your regex fails if there input string contain 5 non-word characters. So for checking the string length, it's better to use .
instead of \w
.
let pwRegex = /^(?=.{5})(?=.*\d{2,})/;
这篇关于正则表达式匹配长度超过 5 个字符且有两个连续数字的密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!