2013-11-28 34 views
0

我想找到一个有效的正则表达式,我可以用它去掉所有的空格或换行符。如何从html文档中去除空白

下面是我试过的东西。

((\ S | \ N |吗?\ r)<(\ S | \ n | \ r)的?)|(\ S | \ n | \ R)>(\ S?| \ n | \ r)的

本文

< tag src="abc" testattribute > 


<script > any script </script > 

<tag2>what is this </tag2> 
<tag> 

上我想最终的结果是正是这一点。

<tag src="abc" testattribute><script>any script</script><tag2>what is this</tag2><tag> 

回答

2

您可以在这里简单地使用\s来匹配空格。

\s matches whitespace (\n, \r, \t, \f, and " ") 

根据您使用的语言,您可以对此使用断言。

(?<=<|>)\s*|(?<!>|<)\s*(?![^><]) 

live demo

正则表达式:

(?<=   look behind to see if there is: 
<    '<' 
    |    OR 
>    '>' 
)    end of look-behind 
\s*   whitespace (\n, \r, \t, \f, and " ") (0 or more times) 
|    OR 
(?<!   look behind to see if there is not: 
>    '>' 
    |   OR 
<    '<' 
)    end of look-behind 
\s*   whitespace (\n, \r, \t, \f, and " ") (0 or more times) 
(?!   look ahead to see if there is not: 
    [^><]  any character except: '>', '<' 
)    end of look-ahead 
+0

我一直在寻找为他人在这里一个JavaScript的解决办法是什么我试着用HWND的解决方案。 (?= <|>)\ S * | – varun

+0

也许尝试|(><)\s*(?![^><]?!):'(?:<|>)|(?!> | <)\s*(?![^><])(\ S *)' – hwnd