正则表达式的HTML文件替换空白 [英] Regex replace whitespace in HTML document

查看:386
本文介绍了正则表达式的HTML文件替换空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多类似的问题,但仍然没有找到答案。结果
应该如何看正则表达式,需要替换所有空格(包括换行符)在HTML中,却忽略了标签?

I saw many similar question, but still not found the answer.
How should look the regex, that needs to replace all whitespaces (include newline) in HTML, but ignore the tag?

目前我使用 Regex.Replace(内容,@\\ S +,); 但在该网页上,比页面不存在的JavaScript删除空间工作原理。

Currently I use Regex.Replace(content, @"\s+", ""); but in removes spaces in JavaScript that exists on page and than the page not works.

感谢您。

修改:在响应,这里多一点点的细节问题,一些经过:
我在做什么是HTTP模块我们的网站上说,minifiesHTML输出。我们有一个网站非常动态的内容,从许多不同的来源。最终的目标,就是减少页大小并减少网络流量。这是一个高负荷的网站,以便完成它的对我们非常重要。

EDIT: After some question in responses, here a little bit more details: What I'm doing is HTTP module that "minifies" HTML output on our site. We have a web site with very dynamic content that came from many different sources. The final goal, is to reduce page size and reduce network traffic. It's a highly loaded web site so it's important to us to complete that.

事实上,我们正在使用的JS和CSS压缩MbCom pression库,但它不支持,以压缩HTML输出(至少我没有找到)。

Actually we are using MbCompression library for JS and CSS minification, but it not supports to minify HTML output (at least i didn't found).

推荐答案

如果你能找到一个像样的HTML解析器,我将通过DOM操作做到这一点。如果不能,那么像

If you can find a decent HTML parser, I would do it via DOM manipulation. If you can't, then something like

Regex.Replace(content, "(?i)(<script(?:[^>\"']|\"[^\"]*\"]|'[^']*')*>)\s+</script\\s*>|<style(?:[^>\"']|\"[^\"]*\"]|'[^']*')*>)\s+</style\\s*>|<textarea(?:[^>\"']|\"[^\"]*\"]|'[^']*')*>)\s+</textarea\\s*>|</?[a-z](?:[^>\"']|\"[^\"]*\"]|'[^']*')*>|\\S+)|\\s+", "$1");

应该这样做。它不会删除空格内标签或内部嵌入的JS,CSS,或内部文字区域,但会删除文本节点换行。

should do it. It will not remove spaces inside tags or inside embedded JS, CSS, or inside textareas but will remove newlines in text nodes.

这篇关于正则表达式的HTML文件替换空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆