-1

The objective is to match strings that are greater than 5 characters long, do not begin with numbers, and have two consecutive digits. I thought my regex was enough to do that but is not matching "bana12".

This regex does the job:

var pwRegex =  /^\D(?=\w{5})(?=\w*\d{2})/;

Is not this regex more restrictive than mine? Why do I have to specify that the two or more digits are preceded by zero or more characters?

involve1
  • 9
  • 2

2 Answers2

0

You were on the right track to maybe use lookaheads, and also with the correct start of your pattern, but it is missing a few things. Consider this version:

^\D(?=.*\d{2})\w{4,}$

Here is an explanation of the pattern:

^                from the start of the string
    \D           match any non digit character
    (?=.*\d{2})  then lookahead and assert that two consecutive digits occur
    \w{4,}       finally match four or more word characters (total of 5 or more characters)
$                end of the string

The major piece missing from your current attempt is that it only matches one non digit character in the beginning. You need to provide a pattern which can match 5 or more characters.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

It is less restrictive than yours.

After the \D, there are 2 lookaheads. For your regex, they are

(?=\w{5})(?=\d{2})

This means that the thing after the non-digit must satisfy both of them. That is,

  • there must be 5 word characters immediately after the non-digit, and
  • there must be 2 digits immediately after the non-digit.

There is ana12 immediately after the non digit in the string. an is not 2 digits, so your regex does not match.

The working regex however has these two lookaheads:

(?=\w{5})(?=\w*\d{2})

It asserts that there must be these two things immediately after the \D:

  • 5 word characters, and
  • a bunch of word characters, followed by two digits

ana12 fits both of those descriptions.

Try this Regex101 Demo. Look at step 6 in the regex debugger. That is when it tries to match the second lookahead.

Sweeper
  • 145,870
  • 17
  • 129
  • 225