Jamie Chien

Jamie Chien • 2023-08-29

Regular Expression 正規表達式 (Regex)

JS Regex

前言

因為突然想寫一篇關於 Regex 的應用,所以才突然出現這個番外篇,至於正在連載中的 Unit Test 和 Javascript 系列就再等等等啊~~~

什麼是 正規表達式?

TL;DR 用簡單字串來描述、符合文中全部符合指定格式的字串

這是一個很酷的技術,在 coding 的過程中,可能常常會有需要比對文字、搜尋、篩選特定文字的需求,又或是要驗證輸入的字串等等情況,這時候只要使用 Regular Expression (以下簡稱 Regex) 就可以輕鬆達到目的囉~

如何使用 Regex ?

以下使用常常被拿來使用的兩個 method 來舉例: test() vs match()

這兩個 method 剛好是相反的,一個是利用 regex 來測試字串,另一個是利用字串來匹配regex,請參考下方,不要用反了喔~

.test()

  • 根據測試結果,將 return true 或 false
/regex/.test('string'); // return true or false

.match()

  • 若沒有找到,將 return null
  • 若有找到,將 return 一個陣列,裡面包含所有成功配對到的字串
'string'.match(/regex/); // return null or Array<string>

特殊字元 (Special Character)

Ignore Case 忽略大小寫 (i)

透過在正規表達式的最後面加上關鍵字 i,可以用來忽略大小寫

Example

let myString = 'Jamie';
let myRegex = /jamie/i; // 在最後面加上i

let result = myRegex.test(myString);

console.log(result); // true

Find More 比對多個成功的結果 (g)

預設沒有加上 g 的話,只要比對到一個就會停止,若想要比對多個,就必須在正規表達式後方加上 g

Example

let myString = 'Repeat, repeat~~~';
let myRegex = /repeat/gi; // 可以同時使用兩個flags

let result = myString.match(myRegex);

console.log(result); // ['Repeat', 'repeat']

Wildcard Period 任意單一字元 (.)

TL;DR 代表任意字元 (Any Character)

概念上很像撲克牌中的鬼牌,在某些遊戲中可以當作任意一張牌的概念。

在正規表達式中,有時候不知道準確的內容,或是在應用上不需要知道的內容,可以使用 . 來代表任意字元,用一個手機號碼的例子來演示:

Example

let myPhone = '0912345678';
let checkPhone = /09./; // 利用.來省略後面的部分

let result = checkPhone.test(myPhone);

console.log(result); // true

Square Bracket 中/方括號 ([])

TL;DR [abc] 代表 Only a, b, or c

配對特定的字元,有時候要一次性的測出或查找所有可能,所以可以利用[] 來將可能的字元一次檢驗出來,這次來透過身分證舉例:

Example

// 已知R,D分別是是台南縣,台南市的代碼

let myID = 'R123456789';
let checkID = /[RD]./; // 透過[RD]一次查找出是否為台南人

let result = checkID.test(myID);

console.log(result); // true

Hyphen 連結號 (-)

有時候要比對的字母太多,就可以利用 - 來定義一個範圍

Example

// 檢查名字中是否含有數字
let myName = 'Jamie';
let checkName = /[0-9]/; // 檢查整個名字是否含有數字

let result = checkName.test(myName);

console.log(result); // false

Caret Character 插入符號/脫字符號 (^)

  • 功能一: 放在正規表達式的最前面位置時,可以比對起始位置
  • 功能二: 既然可以匹配出想要的內容,那當然也可以匹配出不想要的內容,在 [] 裡面的最前面放上 ^ 字元,就可以做出類似於 JS 中 ! 的效果了

Example

// 有時候在創建帳號的時候,要避免用數字作為開頭
let acc = 'account@host.com';
let checkAcc = /^[^0-9]/; // 檢查第一個字是否為數字

let result = checkAcc.test(acc);

console.log(result); // true => 代表不是數字

Any Digit 任何數字 (\d)

TL;DR 簡單說就是任意數字,可以想像成 [0-9]

透過 \d 來匹配任意數字,也可以搭配 +{} 來比對更多或指定數量的數字,以下透過例子來舉例:

Example

let checkDateFormat = /\d{4}-\d{2}-\d{2}/; // 檢查日期格式是否正確

let result1 = checkDateFormat.test('2023-08-29');
let result2 = checkDateFormat.test('2023-8-29');

console.log(result1); // true
console.log(result2); // false

Any Non-digit 任何非數字 (\D)

TL;DR 簡單說就是任意『非』數字

透過 \D 來比對任意非數字

Example

let varName = '0Variable';
let testVariable = /^\D.+/; // 檢查變數名字是否為非數字開頭

let result = testVariable.test(varName);

console.log(result); // false -> 代表此變數名字為數字開頭

Any Alphanumeric 任何字母數字 (\w)

TL;DR 簡單說就是任意英文、數字、底線,可以想像成 [A-Za-z0-9_]

透過 \w 來比對任意字母數字

Example

let username = 'user@example';
let testUsername = /^\w+$/; // 檢查帳號格式是否合法(假設英文、數字、底線以外皆為不合法)

let result = testUsername.test(username);

console.log(result); // false -> 代表不合法

Any Non-Alphanumeric 任何非字母數字 (\W)

TL;DR 簡單說就是任意『非』英文、數字、底線

透過 \W 來比對任意非字母數字

Example

let password = 'my@Password_123';
let testPassword = /\W/; // 檢查密碼格式是否含有不合法的字元(假設英文、數字、底線以外皆為不合法)

let result = testPassword.test(password);

console.log(result); // true -> 代表含有不合法字元

結論

上面列出的是一些常見的正規表達式,正規表達式可以延伸做到非常複雜的判定,在此就不再多撰述了~

還有許多特殊字元也沒有介紹到,以後有機會再補一篇吧~(累了哈哈

謝謝大家花時間看到這邊~~


Reference