What does this regex do?

  • 2
    Why downvote question and then upvote answers? It looks like legit beginner question. It could benefit from some details (e.g. which regex flavour: vim, perl, extended .. or example usage). – Sebastian Oct 17 '14 at 12:36

This regular expression will match HTML comments

In particular:

<!-- matches literal string "<!--"
.    matches any character
*    is a quantifier, it means "0 or more" of the previous character
?    makes the regex non-greedy, so it matches as few times as possible
--> matches literal "-->"

So, your regexp against this text:

blah <!-- first --> yaddahyaddah <!-- second --> other random words.

will match only <!-- first -->.

See http://regex101.com/r/gF7vX2/1

Without the ? it would match everything between the first occurrence of <!-- and the final -->, in other words it would match: <!-- first --> yaddahyaddah <!-- second -->

See http://regex101.com/r/fP4kA3/1

  • <!-- matches the characters <!-- literally
  • . matches any character (except newline)
  • *? is a quantifier that matches the preceding regex between zero and unlimited times, as few times as possible, expanding as needed [lazy]
  • --> matches the characters --> literally

Answer from the regex tester http://regex101.com/r/lA1bH5/2

Note that * matches the preceding regex between zero and unlimited times, as many times as possible.  This is an important distinction.  Consider the following two regexs:

  • A: <!--.*?-->   (the one you asked about)
  • B: <!--.*-->

And consider data line D, which is shown below.  Regex A will find two matches in it; regex B finds only one:

D: <!-- comment one --> HTML <!-- comment two -->

A: (.... match #1 ....)      (.... match #2 ....)
B: (................. match #1 .................)

So regex B will incorrectly treat the HTML between the two comments as if it were in a comment.

  • The explanation by rob is correct. You could use such regular expressions to modify comments in HTML or XML files. – Abrixas2 Oct 17 '14 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.