RT

解决方案 »

  1.   

    HTML is a non-regular language. Like balanced parenthesis, matching balanced HTML tags is impossible to do with Regular Expressions (in CS terms, an NFA or DFA) alone. Impossible as in "halting problem" impossible. You can write complex RegExs that will work on the sample documents you have, but you can never find a correct RegEx that will work on all valid HTML, what to speak of invalid HTML. What you *can* do is use regular expressions to match individual open and close tags and use a stack to keep track of your depth. In CS terms, this would be a Push-down Automata, or PDA.The .NET Regular Expression engine does give away a method to imitate a simple PDA(http://www.oreilly.com/catalog/regex2/chapter/ch09.pdf) Here is a regular expression that will match the balanced <a> tags. (?:<a.*?href=[""'](?<url>.*?)[""'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>)