Greediness works from left to right, but not otherwise. It basically means "don't match unless you failed to match". Here's what's going on:
- The regex engine matches
<br
at the start of the string.
.*?
is ignored for now, it is lazy.
- Try to match
>
, and succeeds.
- Try to match
w
and fails. Now it's interesting - the engine starts backtracking, and sees the .*?
rule. In this case, .
can match the first >
, so there's still hope for that match.
- This keep happening until the regex reaches the slash. Then
>w
can match, but $
fails. Again, the engine comes back to the lazy .*
rule, and keeps matching, until it matches<br><br />A<br />B
Luckily, there's an easy solution: By replacing <br[^>]*>w$
you don't allow matching outside of your tags, so it should replace the last occurrence.
Strictly speaking, this doesn't work well for HTML, because tag attributes can contain >
characters, but I assume it's just an example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…