Piotr Berebecki
Piotr Berebecki

Reputation: 7468

Why my regex does not work when using beginning and end of string anchors?

I have developed the following regex trying to match a string with at least one digit and at least one lowercase character.

(?=.*[a-z])(?=.*\d)

This seems to be working OK. For example it matches 'abc3' and not 'abc'

However as soon as I modify the regex by adding the beginning and end of string anchors it stops working. Would you know why?

^(?=.*[a-z])(?=.*\d)$

Upvotes: 2

Views: 2084

Answers (1)

rock321987
rock321987

Reputation: 11042

$ is terminating the match here. So you are testing basically for a lowercase character and a digit (which is ok). As lookaheads are of zero width, current position of checking does not changes (which by default here is in starting due to ^).

After checking lowercase and digit, you are basically left with ^$ regex which matches empty string (remember the position of matching has not changed because of zero-width property of lookahead).

This is contradictory to your requirements (because there is already a lowercase character and a digit. So string can never be empty. This is causing the regex to fail)

You have to use

^(?=.*[a-z])(?=.*\d).*$

Upvotes: 4

Related Questions