問題描述
我正在使用以下 REGEXP:
I′m using the following REGEXP:
$output = preg_replace( "http:///(.*)\n/", "", $output );
代碼運(yùn)行良好但是!!!!,當(dāng) URL 像 (http://this_is_not_a_comment.com/kickme) 時(shí),代碼會(huì)替換它... (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.
謝謝,
推薦答案
您需要一個(gè)可以區(qū)分代碼和注釋的正則表達(dá)式.特別是,由于//
的序列既可以在字符串中,也可以在注釋中,因此只需區(qū)分字符串和注釋即可.
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.
這是一個(gè)可能會(huì)執(zhí)行此操作的示例:
Here’s an example that might do this:
/(?:([^/"']+|/*(?:[^*]|*+[^*/])**+/|"(?:[^"\]|\.)*"|'(?:[^'\]|\.)*')|//.*)/
在替換函數(shù)中使用它,同時(shí)用第一個(gè)子模式的匹配替換匹配的字符串,然后應(yīng)該能夠刪除 //
樣式注釋.
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.
一些解釋:
[^/"']+
匹配任何不是注釋開頭的字符(//…
和>/*...*/
) 或一個(gè)字符串/*(?:[^*]|*+[^*/])**+/
匹配/* ...*/
樣式注釋"(?:[^"\]|\.)*"
匹配雙引號(hào)中的字符串'(?:[^'\]|\.)*'
匹配單引號(hào)中的字符串//.*
最終匹配//...
樣式注釋.
[^/"']+
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.
由于前三個(gè)結(jié)構(gòu)被分組在一個(gè)捕獲組中,匹配的字符串可用并且當(dāng)用第一個(gè)子模式的匹配替換匹配的字符串時(shí)沒有任何改變.僅當(dāng) //...
樣式的注釋匹配時(shí),第一個(gè)子模式的匹配項(xiàng)為空,因此它被替換為空字符串.
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.
但請注意,這可能會(huì)失敗.我不太確定它是否適用于任何輸入.
But note that this may fail. I’m not quite sure if it works for any input.
這篇關(guān)于類型為//的干凈 JavaScript 注釋的正則表達(dá)式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!