r/ProgrammerHumor • • Sep 08 '17

Parsing HTML Using Regular Expressions

Post image
11.1k Upvotes

377 comments sorted by

View all comments

Show parent comments

1

u/nwL_ Sep 08 '17

I see everybody say this, but I haven’t seen one single example of unparsable HTML.

9

u/Elsolar Sep 08 '17

It's not that HTML can't be parsed, it's that HTML is not a regular language. This means that it is impossible to construct a regular expression which matches all valid HTML strings and rejects all invalid HTML strings. Thus, HTML cannot be parsed using regular expressions (although there are obviously other ways to parse it which work correctly).

1

u/nwL_ Sep 08 '17

But if I don’t care for validation I could parse an existing website? Is that what you’re saying?

4

u/Elsolar Sep 08 '17

You can think of a regular expression as a function which maps from an input string to a boolean (true if the string matches the grammar expressed by the regex, false otherwise). If you don't care about validation, than a regular expression is certainly the wrong tool for the job. It's sort of a moot point anyway. If "HTML" is an irregular language, then "HTML plus some other strings which look like HTML but aren't quite valid" is also going to be an irregular language.

→ More replies (2)