nathnael desta
nathnael desta

Reputation: 11

regex use of D\*

what is the need of adding \D* in this question answer Use lookaheads in the pwRegex to match passwords that are greater than 5 characters long, and have two consecutive digits.

let sampleWord = "bana12";
let pwRegex = /(?=\w{6})(?=\D*\d{2})/; //  this line
let result = pwRegex.test(sampleWord);

i tried without adding \D* in the code but it didn't work, why?

Upvotes: 1

Views: 56

Answers (2)

The fourth bird
The fourth bird

Reputation: 163187

The pattern (?=\w{6})(?=\D*\d{2}) means:

From the current position, assert that directly to the right there are 6 word characters AND optional non digit characters followed by 2 digits.


If you must use a regex to "match passwords that are greater than 5 characters long" then this is not a good pattern.

It will not match ab1c23 which is 6 characters and contains 2 consecutive digits. The reason is because \D can not cross matching the single digit 1 in this case to get to the 23

If you are using .test() you can anchor the regex to the start of the string using ^, use a single lookahead to assert 6 word characters and then match 2 digits:

^(?=\w{6}).*\d\d

See a regex demo.

const regex = /^(?=\w{6}).*\d\d/;
[
  "bana12",
  "abc123",
  "ab1c23",
  "banan1",
  "airplanes",
  "astronaut",
  "123",
  "1234"
].forEach(s =>
  console.log(`${s} --> ${regex.test(s)}`)
)

Upvotes: 0

Alberto Fecchi
Alberto Fecchi

Reputation: 3396

Without the \D*, the second condition would start the match from the position of the two digits, not from the first char.

This will not match:

/(?=\w{6})(?=\d{2})/
testTest12tes

This will match:

/(?=\w{6})(?=\d{2})/
testTest12test

That's because the second example satisfies both condition simultaneously (the second condition (?=\d{2}) without 4 other characters after the two-digits number cause the first condition (?=\w{6}) to fail as 12tes is not a valid 6-character long string. But, when we use 12test, both conditions are evaluated correctly.

The use of \D* let the second condition consider also the characters before the two-digit number, automatically confirming also the first condition.

Upvotes: 0

Related Questions