Find Characters with Lazy Matching -- help

Tell us what’s happening:

I thought I can pass the test without using the ? symbol and I was right. Even in the example if the passed in pattern was /ti/ it would return the same thing.

So what exactly is the function of the ? symbol and can someone give me a better example wherein I’d HAVE to use the ? symbol.

Your code so far


let text = "<h1>Winter is coming</h1>";
let myRegex = /<h1>/; // Change this line
let result = text.match(myRegex);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/find-characters-with-lazy-matching

Hi @avneesh

Imagine you wanted to match the tags of more than just a <h1> element.

<h1>Winter is coming</h1>
<h2>Winter is most definitely coming</h2>
<h3>I promise, winter is nearly here!</h3>
<h4>Okay, maybe it's taking longer than i hoped</h4>

By using /<h1>/ you’re only going to match the h1 tag, however, using /<.*?>/ you will match all tags that have that pattern.

Strictly speaking, the ? will stop the regex from matching whats between the tags as well, because it is a “lazy” modifier and will only match what it needs to, i.e. the starting and closing angle brackets. Where as * is a greedy modifier and will match as much as it possibly can.

That’s really the beauty of Regex, its a pattern matching language that can allow a really complex set of patterns where you won’t know the exact characters you’re trying to match, but rather the structure.

Take a look here and play around with using the ?.

3 Likes

Thanks for the explanation and these website. Is amazing to test our Regular Expressions in it