I have a condition on a password field requiring
- it to be between 5 and 8 characters
- one number should be at least numeric
I’m using:
(?=.*\d).{5,8}
Now the disturbing part is the way, positive conditonal test is used here and secondly, the dot before {}. Could anyone explain ?
The positive lookahead is an anchor: here it will match a position where what follows is an arbitrary set of characters (
.*) followed by a digit (\d).From this position on, there should be any character (
.), 5 to 8 times ({5,8}).Note that a positive lookahead, being an anchor, does not consume any character: this is why it works. Also note that the regex engine will always try to find the leftmost match.
And finally, the regex should also be anchored at the beginning and end (ie,
^(?=.*\d).{5,8}$), otherwise it may match anywhere in the input: the original regex would matchjoizjoeijoiu4ijojiar, without caring for the length specified ({5,8}) as long as a digit is found in the input. The lookahead would matchjoizjoeijoiu4, and.{5,8}would matchjoizjoei.