正則表達式(二)- 位置匹配攻略


正則表達式是匹配模式,要么匹配字符,要么匹配位置。
匹配位置相關知識點內容包括:

什么是位置?
如何匹配位置?
位置的特性

1、什么是位置?

位置(錨)是相鄰字符之間的位置。

2、如何匹配位置?

在ES5中,共有6個錨:^、$、\b、\B、(?=p)、(?!p)

2.1 ^ 和 $

^ (脫字符)匹配開頭,在多行匹配中匹配行開頭。(Begin)
$ (美元符號)匹配結尾,在多行匹配中匹配行結尾。(End)

比如我們把字符串的開頭和結尾用 "#" 替換(位置可以替換成字符的!):

var result = "hello".replace(/^|$/g, '#');
console.log(result); // "#hello#"

多行匹配模式(即有修飾符 m)時,二者是行的概念,這一點需要我們注意:

var result = "I\nlove\njavascript".replace(/^|$/gm, '#');
console.log(result);
/*
#I#
#love#
#javascript#
*/

2.2 \b 和 \B

\b 是單詞邊界,具體就是 \w 與 \W 之間的位置,也包括 \w 與 ^ 之間的位置,和 \w 與 $ 之間的位置。(WordBoundary)

比如考察文件名 "[JS] Lesson_01.mp4" 中的 \b,如下:

var result = "[JS] Lesson_01.mp4".replace(/\b/g, '#');
console.log(result);
// "[#JS#] #Lesson_01#.#mp4#"

\B 就是 \b 的反面的意思,非單詞邊界。例如在字符串中所有位置中,扣掉 \b,剩下的都是 \B 的。(NonWordBoundary)
具體說來就是 \w 與 \w、 \W 與 \W、^ 與 \W,\W 與 $ 之間的位置。

比如上面的例子,把所有 \B 替換成 "#":

var result = "[JS] Lesson_01.mp4".replace(/\B/g, '#');
console.log(result);
// "#[J#S]# L#e#s#s#o#n#_#0#1.m#p#4"

2.3 (?=p) 和 (?!p)

(?=p),其中 p 是一個子模式,即 p 前面的位置,或者說,該位置后面的字符要匹配 p。(Followed by P)

比如 (?=l),表示 "l" 字符前面的位置,例如:

var result = "hello".replace(/(?=l)/g, '#');
console.log(result);
// "he#l#lo"

而 (?!p) 就是 (?=p) 的反面意思(Not followed by p),比如:

var result = "hello".replace(/(?!l)/g, '#');
console.log(result);
// "#h#ell#o#"

3、位置的特性

對於位置的理解,我們可以理解成空字符 ""。

比如 "hello" 字符串等價於如下的形式:

"hello" == "" + "h" + "" + "e" + "" + "l" + "" + "l" + "" + "o" + "";

也等價於:

"hello" == "" + "" + "hello"

因此,把 /^hello$/ 寫成 /^^hello$$$/,是沒有任何問題的:

var result = /^^hello$$$/.test("hello");
console.log(result); // true

甚至可以寫成更復雜的:

var result = /(?=he)^^he(?=\w)llo$\b\b$/.test("hello");
console.log(result);  // true

也就是說字符之間的位置,可以寫成多個。

***TIP *** 把位置理解成空字符,是對位置非常有效的理解方式。


免責聲明!

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



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