正則表達式 中,如何匹配字符串中的 '\'


' \ ' 作為特別功能的轉義字符,在正則表達式有舉足輕重的重要

' \ ' 在字符串中也具有讓某些普通字符變得不普通的能力,比如 ' \t ', ' \n ' 這些眾所周知的;當 '\’ + 某個字符 不具有特殊功能時,加不加其實都沒差別,正則中亦是如此

var str = 'he\tllo';
console.log(str);                // he    llo

 

如何匹配字符串中的 ' \ ' 呢?( 單個 '\' 其實是無法被匹配的 )

 如果用直接量表示正則,作為一個功能字符,想表示自己,當然是需要轉義一下的

 如果用創建 RegExp 對象的方法來寫時,參數1 最好是字符串。 在字符串中,'\' 想表示自己,也需要轉義 '\\' 

1、確定真實的字符串 

2、寫正則表達式

舉個栗子:

str = 'he\llo';
console.log(str);                // hello

var reg = /he\\llo/;
console.log( reg.exec(str) );    // null

reg = /hello/;
console.log( reg.exec(str) );    // ["he\llo", index: 0, input: "he\llo"]
reg = new RegExp('hello');
console.log( reg.exec(str) );
reg = new RegExp('he\llo');
console.log( reg.exec(str) );    
reg = new RegExp('he\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\llo');
console.log( reg.exec(str) );    // ["hello", index: 0, input: "hello"]

reg = /\h\e\l\l\o/;
console.log( reg.exec(str) );    // ["hello", index: 0, input: "hello"]



str = 'he\\llo';
console.log(str);                // he\llo

reg = /he\\llo/;
console.log( reg.exec(str) );    // ["he\llo", index: 0, input: "he\llo"]
reg = new RegExp('he\\\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\\\\llo');
console.log( reg.exec(str) );
reg = new RegExp('he\\\\\\\llo');
console.log( reg.exec(str) );    // ["he\llo", index: 0, input: "he\llo"]

以上,沒有報錯..

蜜汁 ' \ ' 啊,自行體會吧.. 

實際操作中,當然是用盡可能少的字符.. 在最簡 直接量 表示法的基礎上,轉義 

雖然對的情況很多種,擇優


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM