js加固之正規表示式學習筆記

shijf發表於2021-04-02

let regex = /hello/

let str = '1hello world';

let result = regex.test(str)

console.log(result); // true

let result2 = regex.exec(str)

// 'hello' -> 匹配的全部字串

// index: -> 匹配到的字元位於原始字串的基於0的索引值

// input: -> 原始字串

console.log(result2); // [ 'hello', index: 0, input: 'hello world', groups: undefined ]

// flag 

// - i 不區分大小寫

// - g 全域性搜尋 常用於執行一個全域性搜尋匹配, 即(不僅僅返回第一個匹配的, 而是返回全部)

// 元字元 

// - \d 匹配一個數字 相當於 [0-9]

// - \w 匹配一個單字字元(字母或者數字)。等價於 [A-Za-z0-9_]即字母數字字元

// - \s 匹配一個空白字元,包括空格、製表符、換頁符和換行符

// - \t 匹配一個水平製表符

// - \b 匹配一個單詞的開頭和結尾 成為字元界

// - . 匹配一個除換行符之外的任何單個字元

// - \D 匹配一個非數字字元.等價於 [^0-9]

// - \W 匹配一個非單字字元。等價於 [^A-Za-z0-9_] 

// - \S 匹配一個非空白字元 

// 量詞

// + 匹配一個或多個

let regx1 = /\d+/ // 匹配一個或多個的 數字

// 8 true

// 888 ture

// true

console.log(regx1.test('8'));

// true

console.log(regx1.test('88899'));

// true

console.log(regx1.test('8s888845'));

// * 匹配0個或多個

let regx2 = /go*d/

// true

console.log(regx2.test('god'));

console.log(regx2.test('good'));

console.log(regx2.test('good'));

// ? 匹配0個或1個

let regx3 = /go?d/

console.log(regx3.test('god'));

// true

console.log(regx3.test('good'));

// true

console.log(regx3.test('goood'));

// false

// ^ 以什麼開頭

let regx4 = /^g/;

console.log(regx4.test('good'));

// true

console.log(regx4.test('bad'));

// false

console.log(regx4.test('tag'));

// false

// $ 以什麼結尾

let regx5 = /.com$/

console.log(regx5.test('test@testmail.com'));

// true

console.log(regx5.test('test@testmail'));

// false

// 

// {N} 匹配了前面一個字元剛好出現 N 次

// {N, } 匹配了前面一個字元至少出現了 N 次

// {N, M} 匹配了前面一個字元知道出現 N 次,至多出現 M 次

// (x) 匹配x並記住匹配。這些稱為捕獲組。這也用於在正規表示式中建立子表示式。

// (\1) 記住並使用 第一個子表示式中的匹配式 

// (?:x) 匹配x,不記住匹配 這些稱為 非捕獲組 

// (?=y) 只有當 x 後面跟著y,先行後斷言

let regx6 = /red(\s*)(?=apple)/

console.log('regx6.test("red pear")', regx6.test("red pear"));

console.log('regx6.test("red   apple")', regx6.test("red  apple"));

// 202104021440

let str1 = "202104021440"

function format(str) {

    // year 

    let year = /2021/

    // mounth 

    let mouth = 1;

    // day

}

/**

 * [reg 百度網盤連結匹配]

 * 說明:匹配支援百度分享的兩種連結格式

 * 格式一:連結: https://pan.baidu.com/s/15gzY8h3SEzVCfGV1xfkJsQ 提取碼: vsuw 複製這段內容後開啟百度網盤手機App,操作更方便哦

 * 格式二:http://pan.baidu.com/share/link?shareid=179436&uk=3272055266 提取碼: vsuw 複製這段內容後開啟百度網盤手機App,操作更方便哦

 * 匹配出下載地址和提取碼,並且還支援如果沒有提取碼,也能匹配出下載連結。

 * @type {正規表示式}

 * @return array 返回匹配成功的連結和地址

 */

function baiduDownLinkArr( string ){

    var reg = /([http|https]*?:\/\/pan\.baidu\.com\/[(?:s\/){0,1}|(share)]*(?:[0-9a-zA-Z?=&])+)(?:.+:(?:\s)*)?([a-zA-Z]{4})?/;

    console.log(reg.exec(string));

  }

baiduDownLinkArr("https://pan.baidu.com/s/15gzY8h3SEzVCfGV1xfkJsQ")

console.log(str1.replace(/2021/, '2021年'));
本作品採用《CC 協議》,轉載必須註明作者和本文連結
支付寶領個紅包就是對我最大的讚賞了

相關文章