使用正则表达式来删除Flex/AS3中的HTML标签
我正在写Flex(AS3)中的HTML解析器,我需要删除一些不需要的HTML标签。使用正则表达式来删除Flex/AS3中的HTML标签
例如,我想从这个代码中删除的div:
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<p style="padding-left: 18px; padding-right: 20px; text-align: center;">
<span></span>
<span style=" font-size: 48px; color: #666666; font-style: normal; font-weight: bold; text-decoration: none; font-family: Arial;">20% OFF.</span>
<span> </span>
<span style=" font-size: 48px; color: #666666; font-style: normal; font-weight: normal; text-decoration: none; font-family: Arial;">Do it NOW!</span>
<span> </span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
,并用这样的结尾:
<div>
<p style="padding-left: 18px; padding-right: 20px; text-align: center;">
<span></span>
<span style=" font-size: 48px; color: #666666; font-style: normal; font-weight: bold; text-decoration: none; font-family: Arial;">20% OFF.</span>
<span> </span>
<span style=" font-size: 48px; color: #666666; font-style: normal; font-weight: normal; text-decoration: none; font-family: Arial;">Do it NOW!</span>
<span> </span>
</p>
</div>
我的问题是,我怎么能写一个正则表达式删除这些不需要的DIV?有没有更好的方法来做到这一点?
在此先感谢。
假设您的目标HTML实际上是有效的XML,您可以使用递归函数拖出非div位。
static function grabNonDivContents(xml:XML):XMLList {
var out:XMLList = new XMLList();
var kids:XMLList = xml.children();
for each (var kid:XML in kids) {
if (kid.name() && kid.name() == "div") {
var grandkids:XMLList = grabNonDivContents(kid);
for each (var grandkid:XML in grandkids) {
out += grandKid;
}
} else {
out += kid;
}
}
return out;
}
工程完美!谢谢。在这种情况下,我总是确信XML格式正确,我对它有绝对的控制权。所以这个XML解决方案是完美的。 – oscarm 2010-10-01 23:17:49
You can't match arbitrarily nested constructs with a regular expression因为嵌套意味着不规则。一个解析器(您正在编写)是正确的工具。
现在,在这个非常特殊的情况下,你可以做一个
result = subject.replace(/^\s*(<\/?div>)(?:\s*\1)*(?=\s*\1)/mg, "");
(这将直接删除的<div>
或</div>
所有直接后续出现除了最后一个),但是这是不好的在很多方面是恐怕会让我陷入湮没无闻的境地。
为了解释:
^ # match start of line
\s* # match leading whitespace
(</?div>) # match a <div> or </div>, remember which
(?:\s*\1)* # match any further <div> or </div>, same one as before
(?=\s*\1) # as long as there is another one right ahead
你能指望这些这将失败的方法呢? (想想评论,无与伦比的<div>
等)
根据我的经验,解析复杂的HTML与正则表达式只是地狱。正则表达式正在迅速失控。提取您需要的信息(可能与简单的正则表达式)并将其组装成更简单的文档更加稳健。
您是否考虑过使用XML相关类而不是正则表达式来解析您的需求。毕竟HTML是或多或少的XML。检查多个嵌套div标签将会更容易。 – 2DH 2010-09-26 19:04:21