I am a bit confused when it comes to using ‘?’ in Regex syntax.
My understanding is that ‘?’ is used in lazy matching as well as checking for zero or one of the preceding element, so how does one distinguish which scenario ‘?’ is used in in Regexes?
First here is a regex cheat sheet showing all the ways you can use the question mark.
The summary answer to your question is: the interpretation depends on what precedes the question mark.
If it is a regular character or anything that is not a ( then the ? will limit the matches to a maximum of one match, that is a non-greedy match.
If it follows a ( then it becomes part of a something called a “look-ahead” type of match (or look-behind sometimes).
Thanks for your reply! Sorry but I am still a bit confused…using FCC examples
/t[a-z]*?I/ => here ? is used for lazy matching but
/colou?r/ => here ? is implying the preceding element is optional
So how to differentiate?
It is actually kind of the same thing. The ? in both of these limits the match of the previous pattern. But after the character it limits it to 0 or 1 while after the * limits it to a single match.
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.