問題描述
我正在使用以下 REGEXP:
I′m using the following REGEXP:
$output = preg_replace( "http:///(.*)\n/", "", $output );
代碼運行良好但是!!!!,當 URL 像 (http://this_is_not_a_comment.com/kickme) 時,代碼會替換它... (http://)
The code works well BUT!!!!, when a URL like (http://this_is_not_a_comment.com/kickme), the code replaces it... (http://)
你能做些什么來不替換這些 URL.
What can you do to no replace that URLs.
謝謝,
推薦答案
您需要一個可以區分代碼和注釋的正則表達式.特別是,由于//
的序列既可以在字符串中,也可以在注釋中,因此只需區分字符串和注釋即可.
You need a regular expression that can distinguish between the code and the comments. In particular, since the sequence of //
can either be in a string or a comment, you just need to distinguish between strings and comments.
這是一個可能會執行此操作的示例:
Here’s an example that might do this:
/(?:([^/"']+|/*(?:[^*]|*+[^*/])**+/|"(?:[^"\]|\.)*"|'(?:[^'\]|\.)*')|//.*)/
在替換函數中使用它,同時用第一個子模式的匹配替換匹配的字符串,然后應該能夠刪除 //
樣式注釋.
Using this in a replace function while replacing the matched string with the match of the first subpattern should then be able to remove the //
style comments.
一些解釋:
[^/"']+
匹配任何不是注釋開頭的字符(//…
和>/*...*/
) 或一個字符串/*(?:[^*]|*+[^*/])**+/
匹配/* ...*/
樣式注釋"(?:[^"\]|\.)*"
匹配雙引號中的字符串'(?:[^'\]|\.)*'
匹配單引號中的字符串//.*
最終匹配//...
樣式注釋.
[^/"']+
matches any character that is not the begin of a comment (both//…
and/*…*/
) or of a string/*(?:[^*]|*+[^*/])**+/
matches the/* … */
style comments"(?:[^"\]|\.)*"
matches a string in double quotes'(?:[^'\]|\.)*'
matches a string in single quotes//.*
finally matches the//…
style comments.
由于前三個結構被分組在一個捕獲組中,匹配的字符串可用并且當用第一個子模式的匹配替換匹配的字符串時沒有任何改變.僅當 //...
樣式的注釋匹配時,第一個子模式的匹配項為空,因此它被替換為空字符串.
As the first three constructs are grouped in a capturing group, the matched string is available and nothing is changed when replacing the matched string with the match of the first subpattern. Only if a //…
style comment is matched the match of the first subpattern is empty and thus it’s replaced by an empty string.
但請注意,這可能會失敗.我不太確定它是否適用于任何輸入.
But note that this may fail. I’m not quite sure if it works for any input.
這篇關于類型為//的干凈 JavaScript 注釋的正則表達式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!