Your problem is that you're reading a line at a time. This means you don't have the information you need until it's too late. You'd have to switch to reading two lines at a time and that's just silly. But, you'd use a positive lookahead, in-string line anchors, and the sm modifiers.
My criteria for good software:
Does it work?
Can someone else come in, make a change, and be reasonably certain no bugs were introduced?