4 ms·
I agree as far as parsing most HTML. I use regular expressions all the time when I'm working with HTML I've written by hand because I know what's there. I just
by johndcook 14y ago
I agree as far as parsing most HTML. I use regular expressions all the time when I'm working with HTML I've written by hand because I know what's there.
I just find it interesting that the efficacy of regular expressions can be framed as a computer science question, a practical question, and a statistical question.
- fuzzix 14y agoIn practical terms, how often are you actually parsing HTML? Building a DOM, rendering... A knee-jerk reaction to 'HTML' and 'regular expression' being used in the same sentence is like someone seeing 'goto' without understanding the context and shouting "goto considered harmful!" I recently use some combination of perl's split() and regexes to trivially pull all links from a piece of markup. I had to suppress the "Don't parse HTML with regular expressions!" voices echoing in my head the whole time I was writing it. I'm OK with the code now, of course.
- simonster 14y agoIn my experience, an XPath (or CSS selector) to get relevant information is both easier to construct and easier to understand than a regular expression, and the resulting code is more likely to continue to work as the website changes. I don't see why you would subject yourself to using regular expressions unless your environment doesn't have an HTML parser.
- fuzzix 14y agoIn this particular instance, for reasons of a self-imposed contraint to favour ease of deployment and use by the target audience, I have no parser. Using xpath (or just about anything else) would be smashing. The likelihood of the markup changing to the point where the code breaks is unlikely, the target pages are open source mirrors exposed over HTTP. It even winds up being nicer code than the FTP handler.
- johndcook 14y agoGoto statements are a good example. It's easier to recite "goto is harmful" than to say "In most situations, other control structures are more expressive and easier to maintain than goto statements. However, there may be rare occasions, particularly in low-level system programming, where goto statements could be preferable." "Don't parse HTML with regex" is good general advice, but no more an absolute than avoiding goto statements.
- Dylan16807 14y ago>rare occasions, particularly in low-level system programming, where goto statements could be preferable Or something as simple as "break 2;"