C++、Java、JavaScript中的正則表達式

C++(VS2013編譯器):http://msdn.microsoft.com/zh-cn/library/bb982727.aspx#grammarsummaryjavascript

Java:              http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.htmlhtml

JavaScript:         http://www.w3school.com.cn/jsref/jsref_obj_regexp.aspjava

這兒主要是JS中的正則表達式:正則表達式

  1. 正則表達式是用於匹配字符串中字符組合的模式。 一種幾乎能夠在全部的程序設計語言裏和全部的計算機平臺上使用的文字處理工具。它能夠用來查找(搜索)特定的信息,也能夠用來查找並編輯(替換)特定的信息。express

  2. 核心是匹配,匹配位置或者匹配字符。api

  3. 在 JavaScript 中,正則表達式也是對象。數組

  4. 這些模式被用於 RegExp 的 exec 和 test 方法, 以及 String 的 matchreplacesearch 和 split 方法。oracle

二. 建立正則表達式

2.1 正則表達式的建立能夠有如下三種方法。

2.1.1 字面量

/pattern/flags函數

let reg1 = /jing ke tong xue/g; console.log(reg1); // /jing ke tong xue/g
2.1.2 構造函數

new RegExp(pattern [, flags])工具

let reg2 = new RegExp('jing ke tong xue', 'g'); console.log(reg2); // /jing ke tong xue/g
2.1.3 工廠符號

RegExp(pattern [, flags])

let reg3 = RegExp('jing ke tong xue', 'g'); console.log(reg3); // /jing ke tong xue/g

2.2 字面量、構造函數、工廠符號在建立正則表達式中的異同

2.2.1 共同點

三種方法均可以建立正則表達式,正則表達式的文本pattern爲必須參數,標誌符flagsg、i、m、y、u五個可選、可任意搭配參數。

g:(global) 全局模式,即模式將應用於全部的字符串,而非發現第一個匹配項時當即中止;
i: (case-insensitive) 表示不區分大小寫模式
m: (multiline)表示多行模式,即在文本的末尾時會繼續查找下一行是否存在於模式匹配的項
2.2.2 不一樣點

構造函數和工廠符號除了相差一個new關鍵字外沒有什麼不一樣,可是不推薦工廠符號的形式建立正則表達式。下面主要說一下字面量和構造函數的形式建立正則表達式的不一樣之處。

  1. 當表達式被賦值時,字面量形式提供正則表達式的編譯(compilation)狀態,當正則表達式保持爲常量時使用字面量。例如當你在循環中使用字面量構造一個正則表達式時,正則表達式不會在每一次迭代中都被從新編譯(recompiled)

  2. 正則表達式對象的構造函數,如new RegExp('jing ke tong xue')提供了正則表達式運行時編譯(runtime compilation)。若是你知道正則表達式模式將會改變,或者你事先不知道什麼模式,而是從另外一個來源獲取,如用戶輸入,這些狀況均可以使用構造函數。

  3. ECMAScript 6開始,當第一個參數爲正則表達式而第二個標誌參數存在時,new RegExp(/jing ke tong xue/, 'g')再也不拋出==TypeError== (「當從其餘正則表達式進行構造時不支持標誌」)的異常,取而代之,將使用這些參數建立一個新的正則表達式。

  4. 字面量方式pattern中全部字符都是元字符,因此不能進行變量值的拼接。經過構造函數的方式pattern中全部字符都是字符串,是能夠進行字符串拼接的,同時對於特殊字符也是須要轉義的。

  • 字符串變量拼接
const name = 'jing ke'; // 字符串拼接不會成功 let reg1 = /" + name + " tong xue/g; console.log(reg1); // /" + name + " tong xue/g // 字符串拼接能夠成功 let reg2 = new RegExp(name + ' tong xue', 'g'); console.log(reg2); // /jing ke tong xue/g
  • 特殊字符轉義
const name = 'jing ke'; // 匹配name,這裏jing和ke之間可能有1個或多個空格 let reg1 = /jing\s+ke/g; console.log(reg1); // /jing\s+ke/g console.log(reg1.test(name)); // true // 這裏建立的正則表達式和字面量方式建立的結果並不同 let reg2 = new RegExp('jing\s+ke', 'g'); console.log(reg2); // /jings+ke/g console.log(reg2.test(name)); // false // 這裏我把reg3稍稍改造了一下,結果就和reg1同樣了 let reg3 = new RegExp('jing\\s+ke', 'g'); console.log(reg3); // /jing\s+ke/g console.log(reg3.test(name)); // true

再看一個特殊字符轉義的例子

// 寫一個正則表達式匹配反斜槓 \ const str = '\\'; // 這裏str就是 \,反斜槓有特殊意義,下文介紹基本元字符會講 // 字面量方式 let reg1 = /\\/g; console.log(reg1); // /\\/g console.log(reg1.test(str)); // true // 爲何是4個反斜槓,詳見下文元字符介紹。本身在控制檯試試1個,2個,3個會報什麼錯 let reg2 = new RegExp('\\\\', 'g'); console.log(reg2); // /\\/g console.log(reg2.test(str)); // true

三. 正則表達式中特殊字符

3.1 標誌字符

標誌字符 含義
g 全局匹配,找到全部匹配,而不是在第一個匹配後中止。
i 忽略大小寫。
m 多行,將開始和結束字符(^和$)視爲在多行上工做(也就是,分別匹配每一行的開始和結束(由 \n 或 \r 分割),而不僅是隻匹配整個輸入字符串的最開始和最末尾處。
u ES6新增,Unicode,將模式視爲Unicode序列點的序列。
y ES6新增,粘性匹配,僅匹配目標字符串中此正則表達式的lastIndex屬性指示的索引(而且不嘗試從任何後續的索引匹配)。

3.2 基本元字符

基本元字符 含義
. 匹配除了換行符以外的任何單個字符
\ 在非特殊字符以前的反斜槓表示下一個字符是特殊的,不能從字面上解釋。例如,沒有前\b一般匹配小寫b,不管它們出如今哪裏。若是加了\,這個字符變成了一個特殊意義的字符,反斜槓也能夠將其後的特殊字符,轉義爲字面量。例如,模式 /a*/ 表明會匹配0個或者多個a。相反,模式 /a\*/ 將*的特殊性移除,從而能夠匹配像 a* 這樣的字符串。
| 邏輯或操做符。
[...] 定義一個字符集合,匹配字符集合中的一個字符,在字符集合裏面像 .\這些字符都表示其自己。
[^...] 對上面一個集合取非。
- 定義一個區間,例如[A-Z],其首尾字符在 ASCII 字符集裏面。

3.3 數量元字符

量詞 含義
* 等價於{0,},表示出現任意次,能夠不出現。
+ 等價於{1,},表示至少出現一次,上不封頂。
? 等價於{0, 1}表示出現一次或零次。
{m} 等價於{m, m},標誌正好出現m次,不能多也不能少。
{m,} 表示至少出現 m 次,上不封頂。

量詞後面加?能夠實現惰性匹配,對應關係以下:

貪婪量詞 惰性量詞
* *?
+ +?
? ??
{m} {m}?
{m,} {m,}?

3.4 錨字符(位置元字符)

字符 含義
^ 單獨使用匹配表達式的開始。匹配字符串的開頭,在多行檢索中,匹配一行的開頭。
$ 匹配表達式的結束。匹配字符串的結尾,在多行檢索中,匹配一行的結尾。
\b 匹配一個單詞的邊界,簡而言之,就是位於字符\w和字符\W之間的位置,或位於字符\w和字符串的開頭或結尾之間的位置(但須要注意的是在字符組內[\b]匹配的是退格符)。
\B 匹配非單詞邊界。
(?=p) 匹配 p 前面的位置。零寬正向先行斷言,要求接下來的字符都與p匹配,但不能包括匹配p的那些字符。
(?!p) 匹配不是 p 前面的位置。零寬負向先行斷言,要求接下來的字符不與p匹配。

3.5 特殊元字符

字符 含義
\d 等價於[0-9],表示一位數字s。
\D 等價於[^0-9],表示一位非數字。除了ASCⅡ數字以外的任何字符。
\s 等價於[\t\v\n\r\f],表示空白符,包括空格,水平製表符(\t),垂直製表符(\v),換行符(\n),回車符(\r),換頁符(\f)
\S 等價於[^\t\v\n\r\f],表示非空白符。
\w 等價於[0-9a-zA-Z],表示數字大小寫字母和下劃線。
\W 等價於[^0-9a-zA-Z],表示非單詞字符。

四. 正則表達式的一些屬性

4.1 RegExp.lastIndex

  • lastIndex 是正則表達式的一個可讀可寫的整型屬性,用來指定下一次匹配的起始索引。

  • 只有正則表達式使用了表示全局檢索的 "g" 標誌時,該屬性纔會起做用。

若是 lastIndex 大於字符串的長度,則 regexp.test 和 regexp.exec 將會匹配失敗,而後 lastIndex 被設置爲 0。

若是 lastIndex 等於字符串的長度,且該正則表達式匹配空字符串,則該正則表達式匹配從 lastIndex 開始的字符串。

若是 lastIndex 等於字符串的長度,且該正則表達式不匹配空字符串 ,則該正則表達式不匹配字符串,lastIndex 被設置爲 0。

不然,lastIndex 被設置爲緊隨最近一次成功匹配的下一個位置。

請看以下示例代碼:

const str = 'jing ke tong xue jing ke tong xue jing ke tong xue jing ke tong xue'; let reg = /jing ke tong xue/g; // lastIndex從0開始 console.log(reg.lastIndex); // 0 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 16 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 33 // lastIndex可修改 reg.lastIndex = 0; console.log(reg.lastIndex); // 0 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 16 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 33 console.log(reg.test(str)); // false console.log(reg.lastIndex); // 50 console.log(reg.test(str));// true console.log(reg.lastIndex); // 67 console.log(reg.test(str));// false // 上一次匹配失敗,lastIndex重置爲0 console.log(reg.lastIndex); // 0 console.log(reg.test(str));// true

4.2 RegExp.prototype.global

  • global屬性代表正則表達式是否使用了 "g" 標誌。

  • global的值是布爾對象,若是使用了 "g" 標誌,則返回true;不然返回false。 "g" 標誌意味着正則表達式應該測試字符串中全部可能的匹配。

  • global是一個正則表達式實例的只讀屬性。RegExp.prototype.globalwritableenumerableconfigurable屬性均爲false,沒法直接更改此屬性。

請看以下示例代碼:

let reg1 = /jing ke tong xue/; console.log(reg1.global); // false. let reg2 = /jing ke tong xue/g; console.log(reg2.global); // true

4.3 RegExp.prototype.ignoreCase

  • ignoreCase屬性代表正則表達式是否使用了 "i" 標誌。

  • ignoreCase的值是布爾對象,若是使用了"i" 標誌,則返回true;不然,返回false。"i"標誌意味着在字符串進行匹配時,應該忽略大小寫。
  • ignoreCase是正則表達式實例的只讀屬性。RegExp.prototype.ignoreCasewritableenumerableconfigurable屬性均爲false,沒法直接更改此屬性。

請看以下示例代碼:

let reg1 = /jing ke tong xue/; console.log(reg1.ignoreCase); // false. let reg2 = /jing ke tong xue/i; console.log(reg2.ignoreCase); // true

4.4 RegExp.prototype.multiline

  • multiline屬性代表正則表達式是否使用了 "m" 標誌。

  • multiline的值是布爾對象,若是使用了"m" 標誌,則返回true;不然,返回false。"m" 標誌意味着一個多行輸入字符串被看做多行。

  • multiline是正則表達式實例的一個只讀屬性。RegExp.prototype.multilinewritableenumerableconfigurable屬性均爲false,沒法直接更改此屬性。

請看以下示例代碼:

let reg1 = /jing ke tong xue/; console.log(reg1.multiline); // false. let reg2 = /jing ke tong xue/m; console.log(reg2.multiline); // true

4.5 RegExp.prototype.unicode

  • unicode屬性代表正則表達式帶有"u" 標誌。

  • unicode的值是Boolean,而且若是使用了 "u" 標誌則爲true;不然爲false。"u" 標誌開啓了多種Unicode相關的特性。使用 "u" 標誌,任何Unicode 代碼點的轉義都會被解釋。

  • unicode是正則表達式獨立實例的只讀屬性。RegExp.prototype.unicodewritableenumerable屬性爲falseconfigurable屬性均爲true,沒法直接更改此屬性。

請看以下示例代碼:

let reg1 = /jing ke tong xue/; console.log(reg1.unicode); // false. let reg2 = /jing ke tong xue/u; console.log(reg2.unicode); // true

再看以下示例代碼:

// 定義一個四個字節的 UTF-16 編碼的字符 const str = '\uD83D\uDC2A'; let reg1 = /^\uD83D/; // ES5不支持四個字節的 UTF-16 編碼,會將其識別爲兩個字符,故而輸出 true console.log(reg1.test(str)); // true let reg2 = /^\uD83D/u; // 加了u修飾符之後,ES6 就會識別其爲一個字符,故而輸出false console.log(reg2.test(str)); // false

4.6 RegExp.prototype.sticky

  • sticky屬性代表正則表達式帶有"y" 標誌。

  • sticky的值是 Boolean ,而且若是使用了"y"標誌則爲true;不然爲false。"y" 標誌指示搜索是否具備粘性,僅從正則表達式的lastIndex 屬性表示的索引處爲目標字符串匹配(而且不會嘗試從後續索引匹配)。

  • sticky是正則表達式獨立實例的只讀屬性。RegExp.prototype.stickywritableenumerable屬性爲falseconfigurable屬性均爲true,沒法直接更改此屬性。

請看以下示例代碼:

let reg1 = /jing ke tong xue/; console.log(reg1.sticky); // false. let reg2 = /jing ke tong xue/y; console.log(reg2.sticky); // true

再看以下示例代碼:

const str = 'test jing ke tong xue test jing ke tong xue'; let reg1 = /jing ke tong xue/; // 沒有y標識符,lastIndex始終爲0,可是reg1並不具備粘性,並不從lastIndex號爲開始 console.log(reg1.lastIndex); // 0 console.log(reg1.test(str)); // true reg1.lastIndex = 5; console.log(reg1.lastIndex); // 5 console.log(reg1.test(str)); // true // 因爲沒有y標識符,在正則表達式匹配以後,lastIndex又被重置爲0 console.log(reg1.lastIndex); // 0 console.log(reg1.test(str)); // true let reg2 = /jing ke tong xue/y; // 第一次匹配將從0號位開始 console.log(reg2.lastIndex); // 0 console.log(reg2.test(str)); // false // 第二次一次匹配將從5號位開始 reg2.lastIndex = 5; console.log(reg2.lastIndex); // 5 console.log(reg2.test(str)); // true // 下一次匹配將從21號位開始 console.log(reg2.lastIndex); // 21 console.log(reg2.test(str)); // false // 上一次匹配失敗,lastIndex重置爲0;下一次匹配將從0號位開始 console.log(reg2.lastIndex); 

4.7 RegExp.prototype.source

  • source 屬性返回一個值爲當前正則表達式對象的模式文本的字符串。該字符串不會包含正則字面量兩邊的斜槓以及任何的標誌字符。

請看以下示例代碼:

let reg = /jing ke tong xue/gimuy; console.log(reg.source); // jing ke tong xue // source沒法被修改,不會生效 reg.source = 'tong xue jing ke'; console.log(reg); // /jing ke tong xue/gimuy

4.8 RegExp.prototype.flags

  • flagsES6新增屬性,返回一個由當前正則表達式對象的標誌組成的字符串。

  • 標誌以字母表順序排序。(從左到右gimuy)。

  • flags是正則表達式獨立實例的只讀屬性。RegExp.prototype.flagswritableenumerable屬性爲falseconfigurable屬性均爲true,沒法直接更改此屬性。

請看以下示例代碼:

let reg = /jing ke tong xue/gimuy; console.log(reg.flags); // jing ke tong xue // flags沒法被修改,不會生效 reg.flags = 'g'; console.log(reg); // /jing ke tong xue/gimuy

flags屬性爲ES6新增屬性,ES6之前可用以下Polyfill。

if (RegExp.prototype.flags === undefined) { Object.defineProperty(RegExp.prototype, 'flags', { writable: false, // 默認爲false,寫上便於理解 enumerable: false, // 默認爲false,寫上便於理解 configurable: true, get: function() { return this.toString().match(/[gimuy]*$/)[0]; } }); }

五. 正則表達式的一些方法

5.1 RegExp.prototype.test

  • 語法 reg.test(str)str:用來與正則表達式匹配的字符串。

  • test() 方法執行一個檢索,用來查看正則表達式與指定的字符串是否匹配。

  • 若是正則表達式與指定的字符串匹配 ,返回true,不然false

const str = 'jing ke tong xue'; let reg1 = /^jing/; // 判斷str是否是以jing開頭 console.log(reg1.test(str)); // true let reg2 = /^ke/; // 判斷str是否是以ke開頭 console.log(reg2.test(str)); // fase

在設置有全局標誌g的正則使用test方法。

若是正則表達式設置了全局標誌,test方法的執行會改變正則表達式的 lastIndex 屬性。連續的執行test方法,後續的執行將會從 lastIndex 處開始匹配字符串。若是 test 方法返回匹配失敗 false,lastIndex 屬性將會被重置爲0。

const str = 'jing ke tong xue jing ke tong xue jing ke tong xue'; let reg = /jing ke/g; console.log(reg.lastIndex); // 0 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 7 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 24 console.log(reg.test(str)); // true console.log(reg.lastIndex); // 41 console.log(reg.test(str)); // false console.log(reg.lastIndex); // 0

5.2 RegExp.prototype.exec

  • 語法reg.exec(str)str:要匹配正則表達式的字符串。 exec() 方法在一個指定字符串中執行一個搜索匹配。返回一個結果數組或 null

  • 若是匹配成功,exec() 方法返回一個數組,並更新正則表達式對象的屬性。返回的數組將徹底匹配成功的文本做爲第一項,將正則括號裏匹配成功的做爲數組填充到後面。

  • 若是匹配失敗,exec() 方法返回 null

💥若是你只是須要第一個匹配結果,你可能想要使用 RegExp.exec() 。

💥若是你想要得到捕獲組,而且設置了全局標誌,你須要用 String.prototype.match() 。

const str = 'jing ke tong xue jing ke tong xue jing ke tong xue'; let reg = /jing ke/g; console.log(reg.lastIndex); // 0 console.log(reg.exec(str)); // ["jing ke", index: 0, input: "jing ke tong xue jing ke tong xue jing ke tong xue", groups: undefined] console.log(reg.lastIndex); // 7 console.log(reg.exec(str)); // ["jing ke", index: 17, input: "jing ke tong xue jing ke tong xue jing ke tong xue", groups: undefined] console.log(reg.lastIndex); // 24 console.log(reg.exec(str)); // ["jing ke", index: 34, input: "jing ke tong xue jing ke tong xue jing ke tong xue", groups: undefined] console.log(reg.lastIndex); // 41 console.log(reg.exec(str)); // null console.log(reg.lastIndex); // 0

從上述代碼看出,在使用exec時,常常須要配合使用while循環使用:

const str = 'jing ke tong xue jing ke tong xue jing ke tong xue'; let reg = /jing ke/g; let result; // 當reg.exec(str)返回null時結束循環,與上面代碼結果一致 while (result = reg.exec(str)) { console.log(`result: ${result}`, `\nindex: ${result.index}`, `\nlastIndex: ${reg.lastIndex}`, `\ninput: ${result.input}`); } 

5.2 RegExp.prototype.toString

  • 語法reg.toString()

  • toString() 返回一個表示該正則表達式的字符串。

  • RegExp 對象覆蓋了 Object 對象的 toString() 方法,並無繼承 Object.prototype.toString()。對於 RegExp對象,toString() 方法返回一個該正則表達式的字符串形式,同時會將flags屬性按照字母表順序重排。

let reg = /jing ke tong xue/yguim; console.log(reg.toString()); // /jing ke tong xue/gimuy

六. 4種適用於模式匹配的String方法

這裏介紹的4種String方法只是和模式匹配相關的內容,與模式匹配不相關的內容下面並不會說起,若是想了解更多請移步這裏

6.1 String.prototype.search

  • 語法str.search(regexp)

regexp:一個正則表達式(regular expression)對象。若是傳入一個非正則表達式對象,則會使用 new RegExp(obj) 隱式地將其轉換爲正則表達式對象。

  • search() 方法執行正則表達式和 String對象之間的一個搜索匹配。當你想要知道字符串中是否存在某個模式(pattern)時可以使用 search,相似於正則表達式的 test 方法。

  • 若是匹配成功,則 search() 返回正則表達式在字符串中首次匹配項的索引。不然,返回 -1。

💥若是你須要知道一個字符串是否匹配一個正則表達式 RegExp ,可以使用 search() 。

const str = 'jing ke tong xue jing ke tong xue jing ke tong xue jing ke tong xue'; let reg = /jing ke tong xue/g; console.log(str.search(reg)); // 0 // 因爲條件判斷的時候喜歡用true或false, 改造以下, 詳情請自行學習JavaScript位(~)運算符 console.log(!!~str.search(reg)); // true

6.2 String.prototype.match

  • 語法str.match(regexp)

regexp:一個正則表達式對象。若是傳入一個非正則表達式對象,則會隱式地使用 new RegExp(obj) 將其轉換爲一個 RegExp 。若是你未提供任何參數,直接使用 match() ,那麼你會獲得一個包含空字符串的 Array :[""]

  • 當一個字符串與一個正則表達式匹配時, match() 方法檢索匹配項。若是正則表達式不包含 g 標誌,則 str.match() 會返回和 RegExp.exec() 相同的結果。並且返回的 Array 擁有一個額外的 input 屬性,該屬性包含被解析的原始字符串。另外,還擁有一個 index 屬性,該屬性表示匹配結果在原字符串中的索引(以0開始)。

  • 若是正則表達式包含 g 標誌,則該方法返回一個 Array ,它包含全部匹配的子字符串而不是匹配對象。捕獲組不會被返回(即不返回index屬性和input屬性)。若是沒有匹配到,則返回 null 。

在下例中,使用 match 查找 "March" 緊跟着 1 個或多個數值字符,再緊跟着一個逗號「,」,再緊跟着一個或多個空格,接着跟着4個數值字符。正則表達式包含 i 標誌,所以大小寫會被忽略。第二個包含 g 標誌會進行全局匹配。

// 啊,在2018年3月31日的下午,詩性大發,賦詩兩句😎 // 🙈一支穿雲箭, 千軍萬馬來相見🙈 const str = 'In March 31, 2018, An arrow through the clouds to meet thousands upon thousands of horses and soldiers, In March 31, 2018'; let reg1 = /In (march \d+, (\d{4}))/i; let match1 = str.match(reg1); console.log(match1); // 如下是logs內容 // => [ // => "In March 31, 2018", // => "March 31, 2018", // => "2018", // => index: 0, // => input: "In March 31, 2018, An arrow through the clouds to meet thousands upon thousands of horses and soldiers.", // => groups: undefined // => ] // 📒釋疑📌 // "In March 31, 2018" 是整個匹配 // "March 31, 2018" 是被(March \d+, (\d*))捕獲的內容 // "2018" 是被(\d{4}) 捕獲的內容 // index: 0 匹配開始的索引 // input: ... 是被解析的原始字符串 // 這個和上面的差異就是flags多了個g標識符 let reg2 = /In (march \d+, (\d{4}))/ig; let match2 = str.match(reg2); // 多了一個標識符,返回的結果是一個包含匹配字符的數組 console.log(match2); // ["In March 31, 2018", "In March 31, 2018"]

號外,match 方法除了支持正則表達式對象做爲參數外,還支持非正則表達式對象做爲參數。

// 這個例子就不給答案了,好記性不如爛筆頭,有心的同窗請在控制檯輸出結果查看區別😄 const str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript."; const str2 = "4 is 4, 10 is 10, 14 is 14, 40 is 40."; const str3 = "The contract was declared null and void."; console.log(str1.match("number")); console.log(str1.match("NaN")); console.log(str1.match(NaN)); console.log(str1.match("Infinity")); console.log(str1.match(Infinity)); console.log(str1.match(+Infinity)); console.log(str1.match(-Infinity)); console.log(str2.match("10")); console.log(str2.match(10)); console.log(str2.match("-10")); console.log(str2.match(-10)); console.log(str2.match("+10")); console.log(str2.match(+10)); console.log(str3.match("null")); console.log(str3.match(null));

6.3 String.prototype.split

  • 語法str.split([separator[, limit]])

separator: 指定表示每一個拆分應發生的點的字符串。separator 能夠是一個字符串或正則表達式。 若是純文本分隔符包含多個字符,則必須找到整個字符串來表示分割點。若是在str中省略或不出現分隔符,則返回的數組包含一個由整個字符串組成的元素。若是分隔符爲空字符串,則將str原字符串中每一個字符的數組形式返回。

limit: 一個整數,限定返回的分割片斷數量。當提供此參數時,split 方法會在指定分隔符的每次出現時分割該字符串,但在限制條目已放入數組時中止。若是在達到指定限制以前達到字符串的末尾,它可能仍然包含少於限制的條目。新數組中不返回剩下的文本。

split 方法接受兩個參數,返回一個數組。第一個是用來分割字符串的字符或者正則,若是是空字符串則會將元字符串中的每一個字符以數組形式返回,第二個參數可選做爲限制分割多少個字符,也是返回的數組的長度限制。有一個地方須要注意,用捕獲括號的時候會將匹配結果也包含在返回的數組中。

const str = 'jing ke tong xue jing ke tong xue jing ke tong xue'; let reg1 = /\s/; console.log(str.split(reg1)); // => ["jing", "ke", "tong", "xue", "jing", "ke", "tong", "xue", "jing", "ke", "tong", "xue"] console.log(str.split(" ")); // => ["jing", "ke", "tong", "xue", "jing", "ke", "tong", "xue", "jing", "ke", "tong", "xue"] let reg2 = /\s+(tong)\s+/; console.log(str.split(reg2)); // => ["jing ke", "tong", "xue jing ke", "tong", "xue jing ke", "tong", "xue"] let reg3 = /\s+tong\s+/; console.log(str.split(reg3)); // => ["jing ke", "xue jing ke", "xue jing ke", "xue"] console.log(str.split(' tong ')); // => ["jing ke", "xue jing ke", "xue jing ke", "xue"]

6.4 String.prototype.replace

該方法並不改變調用它的字符串自己,而只是返回一個新的替換後的字符串。

在進行全局的搜索替換時,正則表達式需包含 g 標誌。

  • 語法 str.replace(regexp|substr, newSubStr|function)

regexp (pattern): 一個RegExp 對象或者其字面量。該正則所匹配的內容會被第二個參數的返回值替換掉。

substr (pattern): 一個要被 newSubStr 替換的字符串。其被視爲一整個字符串,而不是一個正則表達式。僅僅是第一個匹配會被替換。

newSubStr (replacement): 用於替換掉第一個參數在原字符串中的匹配部分的字符串。該字符串中能夠內插一些特殊的變量名。參考下面的使用字符串做爲參數。

function (replacement): 一個用來建立新子字符串的函數,該函數的返回值將替換掉第一個參數匹配到的結果。參考下面的指定一個函數做爲參數。

replace方法接受兩個參數,第一個是要被替換的文本,能夠是正則也能夠是字符串,若是是字符串的時候不會被轉換成正則,而是做爲檢索的直接量文本。第二個是替換成的文本,能夠是字符串或者函數,字符串可使用一些特殊的變量來替代前面捕獲到的子串。返回一個部分或所有匹配由替代模式所取代的新的字符串。

若是使用字符串做爲參數時替換字符串能夠插入下面的特殊變量名:

變量名 表明的值
$$ 插入一個 "$"。
$& 插入匹配的子串。
$` 插入當前匹配的子串左邊的內容。
$' 插入當前匹配的子串右邊的內容。
$n 假如第一個參數是 RegExp對象,而且 n 是個小於100的非負整數,那麼插入第 n 個括號匹配的字符串。

若是是函數的話,當匹配執行後, 該函數就會執行。 函數的返回值做爲替換字符串。另外要注意的是, 若是第一個參數是正則表達式, 而且其爲全局匹配模式, 那麼這個方法將被屢次調用, 每次匹配都會被調用。

變量名 表明的值
match 匹配的子串。(對應於上述的$&。)
p1, p2, ... 假如replace()方法的第一個參數是一個RegExp 對象,則表明第n個括號匹配的字符串。(對應於上述的$1,$2等。)
offset 匹配到的子字符串在原字符串中的偏移量。(好比,若是原字符串是「abcd」,匹配到的子字符串是「bc」,那麼這個參數將是1)
string 被匹配的原字符串。
const str = '2018-03-31'; let reg = /^(\d{4})\D(\d{2})\D(\d{2})$/; function replacer (match, p1, p2, p3, offset, string) { console.log([match, p1, p2, p3, offset, string]); return [p1, p2, p3].join('/') } console.log(str.replace(reg, replacer)); // => ["2018-03-31", "2018", "03", "31", 0, "2018-03-31"] // => 2018/03/31
相關文章
相關標籤/搜索