自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

移除注釋的完善思路:真的可以用正則實(shí)現(xiàn)?

開發(fā) 前端
網(wǎng)上有很多自稱能實(shí)現(xiàn)移除JS注釋的正則表達(dá)式,實(shí)際上存在種種缺陷。這使人多少有些愕然,也不禁疑惑到:真的可以用正則實(shí)現(xiàn)嗎?而本篇文章以使用正則移除JS注釋為目標(biāo),通過實(shí)踐,由淺及深,遇到問題解決問題,一步步看看到底能否用正則實(shí)現(xiàn)!

移除注釋的完善思路:真的可以用正則實(shí)現(xiàn)?

導(dǎo)語

網(wǎng)上有很多自稱能實(shí)現(xiàn)移除JS注釋的正則表達(dá)式,實(shí)際上存在種種缺陷。這使人多少有些愕然,也不禁疑惑到:真的可以用正則實(shí)現(xiàn)嗎?而本篇文章以使用正則移除JS注釋為目標(biāo),通過實(shí)踐,由淺及深,遇到問題解決問題,一步步看看到底能否用正則實(shí)現(xiàn)!

移除注釋的完善思路:真的可以用正則實(shí)現(xiàn)?

1 單行注釋

單行注釋要么占據(jù)一整行,要么處于某一行的***。

正常情況下不難,直接通過正則匹配,再用replace方法移除便可。 

  1. let codes = `  
  2.   let name = "Wmaker"; // This is name 
  3.   if (name) {  
  4.     // Print name 
  5.     console.log("His name is:"name);  
  6.   }  
  7. `;  
  8.  
  9.  
  10. console.log( codes.replace(/\/\/.*$/mg, '') );  
  11.  
  12. // 打印出:  
  13. // let name = "Wmaker";   
  14. // if (name) {  
  15. //     
  16. //   console.log("His name is:"name);  
  17. // } 

上面是成功的刪除了注釋,不過對于獨(dú)占一整行的注釋清理的不夠徹底,會留下空白行。實(shí)際上,行尾注釋前面的空白也被保留了下來。所以目標(biāo)稍稍提高,清除這些空白。操作起來也并不難,思路大致這樣:刪除整行,實(shí)際上是刪除本行末尾的換行符或上一行末尾的換行符。而換行符本身也屬于空白符。所以只需操作正則,匹配到注釋以及注釋前面所有的空白符即可,一箭雙雕。 

  1. let codes = `  
  2.   let name = "Wmaker"; // This is name 
  3.   if (name) {  
  4.     // Print name 
  5.     console.log("His name is:"name);  
  6.   }  
  7. `;   
  8.  
  9. console.log( codes.replace(/\s*\/\/.*$/mg, '') );  
  10.  
  11. // 打印出:  
  12. // let name = "Wmaker" 
  13. // if (name) {  
  14. //   console.log("His name is:"name);  
  15. // } 

如果在字符串中出現(xiàn)完整的URL地址,上面的正則會直接匹配而將其刪除。網(wǎng)上大多會將URL的格式特征(http://xxx):雙下劃線前面有冒號,作為解決途徑加以利用。但這只是治標(biāo)不治本的做法,畢竟//以任何形式出現(xiàn)在字符串中是它的自由,我們無從干涉。

這樣問題就轉(zhuǎn)變成:如何使正則匹配存在于引號外的雙下劃線?

想匹配被引號包圍,帶有雙下劃線的代碼塊比較簡單:/".*\/\/.*"/mg。難點(diǎn)在于如何實(shí)現(xiàn)這個(gè)否定,即當(dāng)正則匹配到雙下劃線后,再判斷其是否在引號里面?絞盡腦汁,也上網(wǎng)查了很多,都沒有像樣的結(jié)果。靜心平氣,洗把臉?biāo)⑺⒀涝贈_個(gè)頭冷靜之后,覺得單純使用正則的路已經(jīng)走不通了,得跳出這個(gè)圈。

就在***關(guān)頭,在那淫穢污濁的房間上方突然光芒萬丈。我急忙護(hù)住了充滿血絲的眼睛,靜待其適應(yīng)后定睛一看。只見那里顯現(xiàn)出了一段文字(Chinese):孩兒啊,先將帶有//被引號包圍的字符串替換掉,去掉注釋后再還原,不就行了嗎? 

  1. let codes = `  
  2.   let name = "Wmaker"; // This is name 
  3.   if (name) {  
  4.     // Print name 
  5.     console.log("His name is:"name);  
  6.     console.log("Unusual situation, characters of // in quotation marks.");  
  7.   }  
  8. `;   
  9.  
  10. // 之前的方式。  
  11. console.log( codes.replace(/\s*\/\/.*$/mg, '') );  
  12. // 打印出:  
  13. // let name = "Wmaker"
  14. // if (name) {  
  15. //   console.log("His name is:"name);  
  16. //   console.log("Unusual situation, characters of  
  17. // }   
  18.  
  19. // 現(xiàn)在的方式。  
  20. console.log( removeComments(codes) );  
  21. // 打印出: 
  22. // let name = "Wmaker" 
  23. // if (name) {  
  24. //   console.log("His name is:"name);  
  25. //   console.log("Unusual situation, characters of // in quotation marks.");  
  26. // }  
  27.  
  28. function removeComments(codes) {  
  29.   let {replacedCodes, matchedObj} = replaceQuotationMarksWithForwardSlash(codes);  
  30.  
  31.   replacedCodes = replacedCodes.replace(/\s*\/\/.*$/mg, '');  
  32.   Object.keys(matchedObj).forEach(k => {  
  33.     replacedCodes = replacedCodes.replace(k, matchedObj[k]);  
  34.   });  
  35.  
  36.   return replacedCodes;  
  37.  
  38.   function replaceQuotationMarksWithForwardSlash(codes) {  
  39.     let matchedObj = {};  
  40.     let replacedCodes = ''     
  41.  
  42.     let regQuotation = /".*\/\/.*"/mg;  
  43.     let uniqueStr = 'QUOTATIONMARKS' + Math.floor(Math.random()*10000);  
  44.  
  45.     let index = 0;  
  46.     replacedCodes = codes.replace(regQuotation, function(match) {  
  47.       let s = uniqueStr + (index++);  
  48.       matchedObj[s] = match;  
  49.       return s;  
  50.     });  
  51.  
  52.     return { replacedCodes, matchedObj };  
  53.   }  

是的,目標(biāo)達(dá)成了,老天眷顧??!

另外,有一個(gè)需要優(yōu)化的地方:定義字符串的方式有三種 ' " ` ,目前我們只匹配了雙引號。

為了避免正則的記憶功能,都使用了正則字面量進(jìn)行測試。

--- 之前 

  1. console.log( /".*\/\/.*"/mg.test(`'Unu//sual'`) ); // false  
  2. console.log( /".*\/\/.*"/mg.test(`"Unu//sual"`) ); // true  
  3. console.log( /".*\/\/.*"/mg.test(`\`Unu//sual\``) ); // false 

--- 之后 

  1. console.log( /('|"|`).*\/\/.*\1/mg.test(`'Unu//sual'`) ); // true  
  2. console.log( /('|"|`).*\/\/.*\1/mg.test(`"Unu//sual"`) ); // true  
  3. console.log( /('|"|`).*\/\/.*\1/mg.test(`\`Unu//sual\``) ); // true 

?。栴}到此結(jié)束了!

真的結(jié)束了嗎?不!我看了看時(shí)間:02:17,然后將眼鏡摘下,扯了張紙巾,拭去了幾顆淚水。

以下是接連解決的兩個(gè)問題:貪婪模式和轉(zhuǎn)義字符。 

  1. --- STEP 1,由于正則的貪婪模式導(dǎo)致。 
  2. let codes = ` 
  3.   let str = 'abc//abc'; // abc' 
  4. `; 
  5. console.log( codes.match(/('|"|`).*\/\/.*\1/mg) ); // ["'abc//abc'; // abc'"] 
  6.  
  7. -- 解決  
  8. let codes = ` 
  9.   let str = 'abc//abc'; // abc' 
  10. `; 
  11. console.log( codes.match(/('|"|`).*?\/\/.*?\1/mg) ); // ["'abc//abc'"]  
  12.  
  13. --- STEP 2,由定義字符串時(shí)其中的轉(zhuǎn)義字符導(dǎo)致。 
  14. let codes = ` 
  15.   let str = 'http://x\\'x.com'; // 'acs 
  16. `; 
  17. console.log( codes.match(/('|"|`).*?\/\/.*?\1/mg) ); // ["'http://x\'", "'; // '"] 
  18.  
  19. -- 解決  
  20. let reg = /(?<!\\)('|"|`).*?\/\/.*?(?<!\\)\1/mg; 
  21. let codes = ` 
  22.   let str = 'http://x\\'x.com'; // 'acs 
  23. `; 
  24. console.log( codes.match(reg) ); // ["'http://x\'x.com'"

事情到這里,雖然勞累,但多少有些成就感,畢竟成功了。

可是,可是,可是在測試時(shí),竟然無意間發(fā)現(xiàn)一個(gè)無法逾越的障礙。就好比費(fèi)勁千辛萬苦花費(fèi)無盡的財(cái)力物力之后,某某尤物終于愿意一同去情人旅館時(shí),卻發(fā)現(xiàn)家家爆滿,沒有空余的房間。在強(qiáng)裝歡笑,玩命的哄騙著她,一家接連一家的尋找直到終于定到房間后,卻發(fā)現(xiàn)自己已然挺不起來了!

正則會將任意位置的引號作為查找的起始位置,它不在乎引號是成雙的道理。下面是一個(gè)示例。 

  1. let reg = /(?<!\\)('|"|`).*?\/\/.*?(?<!\\)\1/mg;  
  2. let codes = `  
  3.   let str = "abc"; // "  
  4. `;  
  5. console.log( codes.match(reg) ); // [""abc"; // ""] 

不過,問題好歹在補(bǔ)過覺之后的 06:37 時(shí)得以解決。

思路是這樣的:雖然不能正確實(shí)現(xiàn)匹配帶有//被引號包圍的代碼塊(可能有方法,但能力有限),但是簡化成匹配單純被引號包圍的代碼塊,是簡單而且能正確做到的,雖然耗費(fèi)的內(nèi)存多了一些。另外,兩引號間也可能包含換行符,所以為其增加s模式:.代表全部字符。下面是去除單行注釋的最終代碼。 

  1. let codes = `  
  2.   let name = "Wmaker"; // This is name 
  3.   let str = 'http://x\\'x.com' + " / / " + '/"/"/'; // '; // " "  
  4.   if (name) {  
  5.     // Print name 
  6.     console.log("His name is:"name);  
  7.     console.log("Unusual situation, characters of // in quotation marks.");  
  8.   } 
  9. `;  
  10.  
  11. console.log(removeComments(codes));  
  12. // 打印出:  
  13. // let name = "Wmaker" 
  14. // let str = 'http://x\'x.com' + " / / " + '/"/"/' 
  15. // if (name) {  
  16. //   console.log("His name is:"name);  
  17. //   console.log("Unusual situation, characters of // in quotation marks.");  
  18. // } 
  19.  
  20. function removeComments(codes) {  
  21.   let {replacedCodes, matchedObj} = replaceQuotationMarksWithForwardSlash(codes);   
  22.   replacedCodes = replacedCodes.replace(/\s*\/\/.*$/mg, '');  
  23.   Object.keys(matchedObj).forEach(k => {  
  24.     replacedCodes = replacedCodes.replace(k, matchedObj[k]);  
  25.   });  
  26.  
  27.   return replacedCodes;  
  28.  
  29.   function replaceQuotationMarksWithForwardSlash(codes) {  
  30.     let matchedObj = {};  
  31.     let replacedCodes = ''    
  32.  
  33.     let regQuotation = /(?<!\\)('|"|`).*?(?<!\\)\1/smg;  
  34.     let uniqueStr = 'QUOTATIONMARKS' + Math.floor(Math.random()*10000);  
  35.  
  36.     let index = 0;  
  37.     replacedCodes = codes.replace(regQuotation, function(match) {  
  38.       let s = uniqueStr + (index++);  
  39.       matchedObj[s] = match;  
  40.       return s;  
  41.     });  
  42.  
  43.     return { replacedCodes, matchedObj };  
  44.   }  

***補(bǔ)充一點(diǎn),單雙引號雖然也可以多行顯示,但其解析后實(shí)際是單行的。 

  1. let codes = "' \  
  2.   Wmaker \  
  3. '";  
  4. codes.match( /(?<!\\)('|"|`).*?(?<!\\)\1/smg ); // ["'   Wmaker '"] 

2 多行注釋

??!難點(diǎn)已經(jīng)解決,現(xiàn)在就可以悠哉悠哉的往前推進(jìn)了。

多行注釋與單行思路相同,只需在刪除注釋時(shí)多加一個(gè)匹配模式。中和兩者的最終代碼如下。 

  1. let codes = `  
  2.   let name = "Wmaker"; // This is name 
  3.   let str = 'http://x\\'x.com' + " / / " + '/"/"/'; // '; // " "  
  4.   let str = 'http://x\\'x./*a*/com' + " / / " + '/"/"/'; // '; // "/*sad*/ "  
  5.   if (name) {  
  6.     // Print name 
  7.     /* Print name. */  
  8.     console.log("His name is:"name);  
  9.     console.log("Unusual situation, characters of // in quotation marks.");  
  10.     /*  
  11.      * Others test.  
  12.      */  
  13.     console.log("Unusual situation, characters of /* abc */ in quotation marks.");  
  14.   }  
  15. `;   
  16.  
  17. console.log(removeComments(codes));  
  18. // 打印出:  
  19. // let name = "Wmaker" 
  20. // let str = 'http://x\'x.com' + " / / " + '/"/"/' 
  21. // let str = 'http://x\'x./*a*/com' + " / / " + '/"/"/' 
  22. // if (name) {  
  23. //   console.log("His name is:"name);  
  24. //   console.log("Unusual situation, characters of // in quotation marks.");  
  25. //   console.log("Unusual situation, characters of /* abc */ in quotation marks."); 
  26. // }  
  27.  
  28. function removeComments(codes) {  
  29.   let {replacedCodes, matchedObj} = replaceQuotationMarksWithForwardSlash(codes);  
  30.  
  31.   replacedCodes = replacedCodes.replace(/(\s*\/\/.*$)|(\s*\/\*[\s\S]*?\*\/)/mg, '');  
  32.   Object.keys(matchedObj).forEach(k => {  
  33.     replacedCodes = replacedCodes.replace(k, matchedObj[k]);  
  34.   }); 
  35.  
  36.   return replacedCodes;  
  37.   function replaceQuotationMarksWithForwardSlash(codes) {  
  38.     let matchedObj = {};  
  39.     let replacedCodes = ''     
  40.  
  41.     let regQuotation = /(?<!\\)('|"|`).*?(?<!\\)\1/smg;  
  42.     let uniqueStr = 'QUOTATIONMARKS' + Math.floor(Math.random()*10000);  
  43.  
  44.     let index = 0;  
  45.     replacedCodes = codes.replace(regQuotation, function(match) {  
  46.     let s = uniqueStr + (index++);  
  47.     matchedObj[s] = match;  
  48.     return s;  
  49.     });  
  50.     return { replacedCodes, matchedObj };  
  51.   }  

3 總結(jié)

從以上可以得出結(jié)論,單純使用正則表達(dá)式是不能達(dá)到目標(biāo)的,需要配合其它操作才行。但現(xiàn)在得出的結(jié)果真的能覆蓋全部的情況?會不會有其它的隱藏問題,比如多字節(jié)字符的問題。雖然作為一個(gè)碼農(nóng),該有的自信不會少,但慢慢的也明白了自己的局限性。從網(wǎng)上的其它資料看,使用UglifyJS,或在正確的解析中去除注釋,會更為穩(wěn)妥。但有可能自己動手解決的,沒理由不花費(fèi)些精力試試!

問題更新記錄

感謝熱心同志找出的錯(cuò)誤,我會將能改與不能改的都列于此地,并只會更新下面兩個(gè)示例的代碼。

1.沒有考慮正則字面量中的轉(zhuǎn)義字符。

出錯(cuò)示例:var reg=/a\//;。

修改方式:將刪除注釋的正則改為:/(\s*(?<!\\)\/\/.*$)|(\s*(?<!\\)\/\*[\s\S]*?(?<!\\)\*\/)/mg。

這里是工作于前端頁面的代碼及相應(yīng)示例,下載鏈接。 

  1. <!DOCTYPE html>  
  2. <html> 
  3.  
  4. <head>  
  5.   <meta charset="UTF-8" 
  6.   <title>Remove Comments</title>  
  7. </head>  
  8.  
  9. <body>  
  10.   <p>輸入:</p>  
  11.   <textarea id="input" cols="100" rows="12"></textarea>  
  12.  
  13.   <br /><br />  
  14.   <button onclick="transform()">轉(zhuǎn)換</button>  
  15.  
  16.   <p>輸出:</p>  
  17.   <textarea id="output" cols="100" rows="12"></textarea>    
  18.  
  19.   <script>  
  20.     let input = document.querySelector('#input');  
  21.     let output = document.querySelector('#output');  
  22.  
  23.     setDefaultValue();  
  24.  
  25.     function transform() {  
  26.       output.value = removeComments(input.value);  
  27.     } 
  28.  
  29.     function removeComments(codes) {  
  30.       let {replacedCodes, matchedObj} = replaceQuotationMarksWithForwardSlash(codes);  
  31.  
  32.       replacedCodes = replacedCodes.replace(/(\s*(?<!\\)\/\/.*$)|(\s*(?<!\\)\/\*[\s\S]*?(?<!\\)\*\/)/mg, '');  
  33.       Object.keys(matchedObj).forEach(k => { 
  34.        replacedCodes = replacedCodes.replace(k, matchedObj[k]);  
  35.       });  
  36.  
  37.       return replacedCodes;  
  38.  
  39.       function replaceQuotationMarksWithForwardSlash(codes) {  
  40.         let matchedObj = {};  
  41.         let replacedCodes = ''         
  42.  
  43.         let regQuotation = /(?<!\\)('|"|`).*?(?<!\\)\1/smg;  
  44.         let uniqueStr = 'QUOTATIONMARKS' + Math.floor(Math.random()*10000);  
  45.  
  46.         let index = 0;  
  47.         replacedCodes = codes.replace(regQuotation, function(match) {  
  48.           let s = uniqueStr + (index++);  
  49.           matchedObj[s] = match;  
  50.           return s;  
  51.         });  
  52.  
  53.         return { replacedCodes, matchedObj };  
  54.       }  
  55.     }  
  56.  
  57.     function setDefaultValue() {  
  58.       input.value = `let name = "Wmaker"; // This is name 
  59. let str = 'http://x\\'x.com' + " / / " + '/"/"/'; // '; // " "  
  60. let str = 'http://x\\'x./*a*/com' + " / / " + '/"/"/'; // '; // "/*sad*/ "  
  61. if (name) {  
  62.   // Print name 
  63.   /* Print name. */  
  64.   console.log("His name is:"name);  
  65.   console.log("Unusual situation, characters of // in quotation marks.");  
  66.   /*  
  67.    * Others test.  
  68.    */  
  69.   console.log("Unusual situation, characters of /* abc */ in quotation marks."); 
  70.   
  71. `;  
  72.     }  
  73.   </script>  
  74. </body>  
  75. </html> 

這里是工作于Node端的代碼及相應(yīng)示例,下載鏈接。運(yùn)行命令:node 執(zhí)行文件 待轉(zhuǎn)譯文件 轉(zhuǎn)移后文件。 

  1. const fs = require('fs');  
  2. const path = require('path');  
  3. const process = require('process');  
  4.  
  5. let sourceFile = process.argv[2];  
  6. let targetFile = process.argv[3];  
  7. if (!sourceFile || !targetFile) {  
  8.   throw new Error('Please set source file and target file.');  
  9.  
  10. sourceFile = path.resolve(__dirname, sourceFile);  
  11. targetFile = path.resolve(__dirname, targetFile);  
  12.  
  13. fs.readFile(sourceFile, 'utf8', (err, data) => {  
  14.   if (err) throw err; 
  15. fs.writeFile(targetFile, removeComments(data), 'utf8', (err, data) => {  
  16.     if (err) throw err;  
  17.     console.log('Remove Comments Done!');  
  18.   });  
  19. });  
  20.  
  21. function removeComments(codes) {  
  22.   let {replacedCodes, matchedObj} = replaceQuotationMarksWithForwardSlash(codes);  
  23.  
  24.   replacedCodes = replacedCodes.replace(/(\s*(?<!\\)\/\/.*$)|(\s*(?<!\\)\/\*[\s\S]*?(?<!\\)\*\/)/mg, '');  
  25.   Object.keys(matchedObj).forEach(k => {  
  26.     replacedCodes = replacedCodes.replace(k, matchedObj[k]);  
  27.   }); 
  28.   
  29.   return replacedCodes; 
  30.  
  31.   function replaceQuotationMarksWithForwardSlash(codes) {  
  32.     let matchedObj = {};  
  33.     let replacedCodes = ''      
  34.  
  35.     let regQuotation = /(?<!\\)('|"|`).*?(?<!\\)\1/smg;  
  36.     let uniqueStr = 'QUOTATIONMARKS' + Math.floor(Math.random()*10000);  
  37.  
  38.     let index = 0;  
  39.     replacedCodes = codes.replace(regQuotation, function(match) {  
  40.       let s = uniqueStr + (index++);  
  41.       matchedObj[s] = match;  
  42.       return s;  
  43.     });  
  44.  
  45.     return { replacedCodes, matchedObj };  
  46.   }  
責(zé)任編輯:龐桂玉 來源: segmentfault
相關(guān)推薦

2022-09-20 15:33:35

JavaScriptCSS編程

2021-11-16 12:25:14

jsPPT前端

2020-07-24 09:40:04

C語言OOP代碼

2018-07-31 10:20:54

WindowsDocker Linux

2023-10-24 08:25:20

TCC模式事務(wù)

2012-02-08 09:28:59

無線網(wǎng)絡(luò)Wi-FiRuckus

2011-01-21 13:56:44

SendmailSolaris

2011-01-04 14:27:50

安裝linux方法

2022-06-06 12:02:23

代碼注釋語言

2023-04-03 08:26:01

systemd運(yùn)維

2009-12-03 10:27:12

FreeBSD路由器Snort

2011-06-17 14:36:50

Linux

2017-10-11 16:16:29

弱電pvc管穿線

2010-04-02 15:36:37

Oracle約束

2020-07-16 08:32:16

JavaScript語言語句

2023-08-22 09:00:00

人工智能Fashion-AI

2015-04-27 11:09:53

GoogleQUIC互聯(lián)網(wǎng)協(xié)議

2022-11-21 10:28:13

FlutterPython

2020-11-03 07:43:24

MQ版本號程序員

2024-03-08 10:48:10

GoRust高性能
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號