title: Regex to match html open and close tags(need some explanation)
body: <p>I have difficulties in understanding some nuances in regular expressions. I am following the tutorial <a href="http://www.regular-expressions.info/backref.html" rel="nofollow">http://www.regular-expressions.info/backref.html</a> and stuck on the example of matching open and close tag using <code>backreferences</code>.</p>
  
  <p>We have string:</p>
  
  <pre><code>Testing &lt;B&gt;&lt;I&gt;bold italic&lt;/I&gt;&lt;/B&gt; text
  </code></pre>
  
  <p>and expression:</p>
  
  <pre><code>&lt;([A-Z][A-Z0-9]*)\b[^&gt;]*&gt;.*?&lt;/\1&gt;
  </code></pre>
  
  <p>I can understand the whole logic, but can not get why engine backtracks to dot:</p>
  
  <blockquote>
    <p>The engine has now arrived at the second <code>&lt;</code> in the regex, and the
    second <code>&lt;</code> in the string. These match. The next token is <code>/</code>. This does
    not match <code>I</code>, and the engine is forced to backtrack to the dot. The dot
    matches the second <code>&lt;</code> in the string. The star is still lazy, so the
    engine again takes note of the available backtracking position and
    advances to <code>&lt;</code> and <code>I</code>. These do not match, so the engine again
    backtracks.</p>
  </blockquote>
  
  <p>Why it backtracks to dot? Is this because we have successfully matched the previous part of regex and it always backtracks to the position of previous successful match + 1?</p>
  
  <p>And the second part I can not get completely. If we have a string:</p>
  
  <pre><code>Testing &lt;BOO&gt;&lt;I&gt;bold italic&lt;/I&gt;&lt;/B&gt; text
  </code></pre>
  
  <p>and expression without word boundary:</p>
  
  <pre><code>&lt;([A-Z][A-Z0-9]*)[^&gt;]*&gt;.*?&lt;/\1&gt;
  </code></pre>
  
  <blockquote>
    <p>...and look inside the regex engine at the point where <code>\1</code> fails the
    first time. First, <code>.*?</code> continues to expand until it has reached the
    end of the string, and <code>&lt;/\1&gt;</code> has failed to match each time <code>.*?</code> matched
    one more character.</p>
    
    <p>Then the regex engine backtracks into the capturing group. <code>[A-Z0-9]*</code> has matched <code>oo</code>, but would just as happily match <code>o</code> or nothing at all. When backtracking, <code>[A-Z0-9]*</code> is forced to give up one character.</p>
  </blockquote>
  
  <p>Why it backtracks into the capturing group and not to dot as in previous example? And I can not get why <code>[A-Z0-9]*</code> is forced to give up one character? Is there some general rule where engine will backtrack?</p>