正規式不是簡單好學的-2

前言

延續上篇,緊接著實實際演練,小旗標參數 g 、 i 、 m (皆為ES6之前的參數),與其使用方法。

小旗標參數

先前說過有兩種宣告正規式的用法,第一個使用雙斜線(//),第二個是使用建構式(RegExp())

g (全域搜尋 - Global)

在文章中,先說只有一行文字,要搜尋一個以上的關鍵字,就特別容易,如果說不加g的話,只會找到第一個符合關鍵字的。

1
2
/test/.test("這是Test、test、test、TesT、TeSt");
=> true (有找到)

在這使用 test() 方法,很難去判定所找到的那哪個字,只會告訴你說我已找到囉,並回傳 truefalse,但現在應該使用 match(),但這方法不是由 RegExp 所提供,此方法為 String 原型的方法,使用用法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"字串".match(/正規式語法/);
//match裡,參數若不是正規式,將會自動轉型。
//如不傳參數,將回傳 [""]

//例 1:
"Example_ABC123_@gmail.com".match(/[ABC]{3}/);
=> ["ABC", index: 8, input: "Example_ABC123_@gmail.com", groups: undefined]

//例 2:
"這是Test、test、test、TesT、TeSt".match(/test/g);
=> (2)["test", "test"]

//例 3 :
"Example_ABC123_@gmail.com".match(/([\w]{7})_(\w{6})_@gmail/);

使用match(),將會回傳陣列,區分為有無使用 g
使用 g 將回傳,所有符合關鍵字的字串
使用 g 將回傳

i (不分大小寫)

在文章、句子中有可能英文字出現很多次,同樣英文單字出現,但如果不使用 i 將只會找到同關鍵字的字串,先來使用幾個小範例

1
2
3
4
5
6
7
//例 1 : 如果不使用 i 將會找到兩個 test
"這是Test、test、test、TesT、TeSt".match(/test/g);
=> (2)["test", "test"]

//例 2 : 使用 i 將會找到全部
"這是Test、test、test、TesT、TeSt".match(/test/gi);
=> (5) ["Test", "test", "test", "TesT", "TeSt"]

m (多行模式)

如有斷句將被採用。

1
2
3
4
5
6
7
//例 1 : 使用 m
"這是Test、test、\ntest、TesT\n、TeSt".match(/test/m);
=> ["test", index: 7, input: "這是Test、test、↵test、TesT↵、TeSt", groups: undefined]

//例 2 : 使用 m 和 g
"這是Test、test、\ntest、TesT\n、TeSt".match(/test/gm);
=> (2)["test", "test"]

如果用了多行,不使用 g 將有可能找不到其他關鍵字。

結語

簡易紀錄小旗標用法,下回待續

0%