您能否提供一些示例说明为什么使用正则表达式难以解析 XML 和 HTML?

2022-01-30 00:00:00 xml regex html

我看到人们犯了一个错误 over 和 再次 正在尝试使用正则表达式解析 XML 或 HTML.以下是解析 XML 和 HTML 困难的几个原因:

One mistake I see people making over and over again is trying to parse XML or HTML with a regex. Here are a few of the reasons parsing XML and HTML is hard:

人们希望将文件视为一系列行,但这是有效的:

People want to treat a file as a sequence of lines, but this is valid:

<tag
attr="5"
/>

人们想要对待 <或 <tag 作为标签的开始,但是这样的东西在野外存在:

People want to treat < or <tag as the start of a tag, but stuff like this exists in the wild:

<img src="imgtag.gif" alt="<img>" />

人们通常希望将开始标签与结束标签匹配,但 XML 和 HTML 允许标签包含自己(传统的正则表达式根本无法处理):

People often want to match starting tags to ending tags, but XML and HTML allow tags to contain themselves (which traditional regexes cannot handle at all):

<span id="outer"><span id="inner">foo</span></span> 

人们经常希望匹配文档的内容(例如著名的查找给定页面上的所有电话号码"问题),但数据可能会被标记(即使在查看时看起来很正常):

People often want to match against the content of a document (such as the famous "find all phone numbers on a given page" problem), but the data may be marked up (even if it appears to be normal when viewed):

<span class="phonenum">(<span class="area code">703</span>)
<span class="prefix">348</span>-<span class="linenum">3020</span></span>

评论可能包含格式错误或不完整的标签:

Comments may contain poorly formatted or incomplete tags:

<a href="foo">foo</a>
<!-- FIXME:
    <a href="
-->
<a href="bar">bar</a>

您还知道哪些其他问题?

What other gotchas are you aware of?

推荐答案

这里有一些有趣的有效 XML:

Here's some fun valid XML for you:

<!DOCTYPE x [ <!ENTITY y "a]>b"> ]>
<x>
    <a b="&y;>" />
    <![CDATA[[a>b <a>b <a]]>
    <?x <a> <!-- <b> ?> c --> d
</x>

这个小小的快乐是有效的HTML:

And this little bundle of joy is valid HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" [
    <!ENTITY % e "href='hello'">
    <!ENTITY e "<a %e;>">
]>
    <title>x</TITLE>
</head>
    <p id  =  a:b center>
    <span / hello </span>
    &amp<br left>
    <!---- >t<!---> < -->
    &e link </a>
</body>

更不用说所有针对无效结构的特定于浏览器的解析.

Not to mention all the browser-specific parsing for invalid constructs.

祝你好运!

编辑(Jörg W Mittag):这是另一个很好的格式良好、有效的 HTML 4.01:

EDIT (Jörg W Mittag): Here is another nice piece of well-formed, valid HTML 4.01:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd"> 
<HTML/
  <HEAD/
    <TITLE/>/
    <P/>

相关文章