Why does this answer work for "Find Characters with Lazy Matching"?

yes that would be what I am referring to :slight_smile:

I’m unsure what you’re asking.

Basically when using regex, the stuff inside the // are rules to match. It will search and do it’s utmost to satisfy exactly what you command it.

In the case of the regex test of /<h1>/, you’re telling regex, I want to search through text for anything that matches <h1> exactly.

How does regex know to find h1 using only .*?

I explained earlier why it does that.

The short version is that:

  1. following * or + with ?, makes the search lazy, which means that it will return the least amount of chars to satisfy your command
  2. Because you surround the .*? with < and >, you giving the regex more rules to follow.
1 Like

Thanks for taking the time to explain this for me. I think I have a better understanding now but the only thing is why h1 instead of h if ? reduces the amount of characters to be returned?

For the purposes of the exercise, I believe that /<h>/ will give you undefined.

Also, if you want to use the html, use the backslash before the <
Like \<

1 Like

Lol, thanks so much!

So just to get this straight, <h> would work in a regular setting instead of <h1> (when using the .*?) ?

It depends on what you are looking for, but if you are going to use regex on an html file, you will most likely not find anything that has just <h>

1 Like

Thank you so much for explaining! :slight_smile:

Forgot to be explicit. No, /<h>/ Will not work. The reason why /<h1>/ will give you the same answer as the tests are looking for is that you are being explicit/precise with your search.

1 Like

Thanks for taking the time to explain this for me. I think I have a better understanding now but the only thing is why h1 instead of h if ? reduces the amount of characters to be returned?

I understood your question differently and wanted to provide my input, late as it is.

/<.*?>/ will return an answer of <h1> not <h> because the string being tested is <h1>Winter is coming</h1>

If the string being tested was <h>Winter is coming</h> then the returning answer would have been <h>

The reason is that the regex /<.*?>/ is looking for any character (except for a space) using the . symbol between a < and a >. Combined with the * symbol, it’s looking for any character 0 or more times. Since there are two characters between < and > that full phrase is returned.

In other words, if the string being tested were <h123456>Winter is coming</h123456> then the answer would be <h123456>.

Or if the string being tested were <h1><h><h123456>Winter is coming</h123456></h></h1> then the answer would be <h1> because it returns the first answer that matches its criteria.

1 Like