Viji
Viji

Reputation: 2629

Difference between LookaHead RegEx and other one?

Can anyone please let me know which is the best solution?

I'm trying to get the 5 to 10 characters, at least one letter, no special characters, characters in \w is acceptable.

and the second one is checking for minimum length 5 but not validating for maximum length. why?

    ^(?=.{5,10}$)(\w*[a-z]\w*)$

    ^(\w*[a-z]\w*){5,10}$

Thanks, Viji

Upvotes: 1

Views: 44

Answers (2)

zx81
zx81

Reputation: 41838

In the comments to Bergi's (correct) answer, you asked for a way to match your string without a lookahead.

Here is one. It's a neat regex trick, but it doesn't make the regex simpler than when you were using a lookahead.

^(?:([a-z])|[_0-9]){5,10}(?(1)|^)$

This will work in regex flavors that support conditionals, such as .NET, PCRE, Python and Ruby.

How does it work?

  1. (?:([a-z])|[_0-9]) matches exactly one character. To specify the characters, we use an alternation |. If the character is a letter, the parentheses in ([a-z]) capture it to Group 1.
  2. The {5,10} quantifier make sure that we match the right number of characters
  3. The (?(1)|^) is a conditional that checks if capture Group1 has been set. If it has been set (the left side of the |), no action is taken. If Group 1 has not been set (the right side of the |), that means we have not matched a single letter, and the ^ beginning of string assertion forces the regex to fail.

Upvotes: 2

Bergi
Bergi

Reputation: 664297

Because in the second one, the whole group (\w*[a-z]\w*) is allowed to be repeated from 5 to 10 times.

And in that group, you have any number of \w characters allowed.

What you might want to use instead is

^(?=.*?[a-z])\w{5,10}$

but your first expression is fine as well. I don't think there's an easy solution without lookahead.

Upvotes: 2

Related Questions