正則表達式位置匹配
正則表達式是匹配模式,要麼匹配字符,要麼匹配位置。
位置
位置(錨)是相鄰字符之間的位置。比如,下圖中箭頭所指的地方:
匹配位置
ES5中,共有6個錨:^
,$
,\b
,\B
,(?=p)
,(?!p)
。
位置可以替換成字符的
脫字符^ 和 美元符$
^
匹配開頭,在多行匹配中匹配行開頭。
$
匹配結尾,在多行匹配中匹配行結尾。
單行匹配模式
//將hello中的^或者$位置替換爲#
var result = "hello".replace(/^|$/g, '#');
console.log(result);
// => "#hello#"
多行匹配模式(有修飾符m)
//\n是換行,所以三個單詞分爲三行,將每行的開頭結尾均替換爲#
var result = "I\nlove\njavascript".replace(/^|$/gm, '#');
console.log(result);
/*
#I#
#love#
#javascript#
*/
單詞邊界\b 和 非單詞邊界\B
\b
具體就是 \w
與 \W
之間的位置,也包括 \w
與 ^
之間的位置,和 \w
與 $
之間的位置。(\w
包括數字、大小寫字母和下劃線 ,\W
表示除\w之外的所有字符,^
表示行開頭 ,$
表示行結尾)
比如考察文件名 "[JS] Lesson_01.mp4"
中的 \b
,如下:
//\b是字符和非字符的交界處
var result = "[JS] Lesson_01.mp4".replace(/\b/g, '#');
console.log(result);
// => "[#JS#] #Lesson_01#.#mp4#"
\B
就是 \b
的反面的意思,非單詞邊界。在字符串中所有位置中,扣掉 \b
,剩下的都是 \B
的。 包括\w
與 \w
、 \W
與 \W
、^
與 \W
,\W
與 $
之間的位置。
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"
(?=p) 和 (?!p)
(?=p)
匹配 p 前面的位置,學名爲正向先行斷言。
例如:
//匹配字符'l'前面的位置
var result = "hello".replace(/(?=l)/g, '#');
console.log(result);
// => "he#l#lo"
(?!p)
就是 (?=p)
的反面意思,學名爲負向先行斷言。比如:
var result = "hello".replace(/(?!l)/g, '#');
console.log(result);
// => "#h#ell#o#"
位置的特性
對於位置的理解,我們可以理解成空字符 “”。
"hello" == "" + "h" + "" + "e" + "" + "l" + "" + "l" + "" + "o" + "";