When quantifying a regex as lazy, such as \w{2,4}?, is it any more or less efficient than otherwise (greedy) when asserted as the beginning and end of the test?
e.g. ^\w{2,4}?$ vs ^\w{2,4}$ testing '12345' '1234'
Both won't match your test string because your input contains 5 characters where your regex only matches the string which has 2 to 4 characters. This ? won't be needed when anchors are used. ^.*?$ does the same as ^.*$. And i suggest you to use ^\w{2,4}$ instead of ^\w{2,4}?$. The second one takes 8 steps to find the match where the first one would take 5 steps to find a match.
DEMO
Let us consider 1234 as a sample string.
^\w{2,4}$
From the start, the above regex would match all the chars which ranges from 2 to 4 characters greedily and the $ anchor asserts that we are at the end.
^\w{2,4}?$
But when we use this, it matches upto the two characters and checks for end of the line. Because there isn't an end of the line anchor next to the second character, it matches the third character and again check for the end of the line anchor next to that third character. Result is no, so it moves to the next character and matches it. Now it check for the end of the line anchor. Yes, it's an end of the line. If it has any character following the fourth character then it discards it's operation. This is the reason for taking more number of steps than the greedy one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With