Contents

Regex 實用整理

整理開發中常用的 Regex 樣式,包含驗證格式和文字處理,每個樣式附上說明和範例。

Email 驗證

1
^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$

範例匹配:user@example.comuser.name+tag@sub.domain.org


URL 驗證

1
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

範例匹配:https://www.example.comhttp://sub.domain.org/path/to/page


台灣手機號碼(09 開頭)

1
^09\d{8}$

範例匹配:0912345678

若需要允許加號或國碼格式(+886):

1
^(\+886|0)9\d{8}$

台灣身分證字號

1
^[A-Z][12]\d{8}$
  • 第一碼:大寫英文字母(縣市代碼)
  • 第二碼:1(男性)或 2(女性)
  • 後八碼:數字

範例匹配:A123456789


IP 位址(IPv4)

1
^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$

範例匹配:192.168.1.110.0.0.1255.255.255.0


日期格式(YYYY-MM-DD)

1
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$

範例匹配:2024-01-152023-12-31


移除 HTML 標籤

1
<[^>]+>

使用方式(JavaScript):

1
2
3
const text = '<p>Hello <b>World</b></p>';
const clean = text.replace(/<[^>]+>/g, '');
// 結果:'Hello World'

移除前後空白字元

1
^\s+|\s+$

使用方式(JavaScript):

1
2
3
const str = '   hello world   ';
const trimmed = str.replace(/^\s+|\s+$/, '');
// 結果:'hello world'

現代 JavaScript 可直接使用 str.trim(),但 Regex 在其他語言或需要自訂空白定義時很有用。


移除連續空白

1
\s{2,}

使用方式:

1
2
3
const str = 'hello    world   foo';
const result = str.replace(/\s{2,}/g, ' ');
// 結果:'hello world foo'

數字驗證

1
2
3
4
5
6
7
8
# 整數(含負數)
^-?\d+$

# 正整數
^\d+$

# 浮點數
^-?\d+(\.\d+)?$

中文字元

1
[\u4e00-\u9fff]

匹配常用中文字(CJK 統一漢字範圍)。

使用方式:

1
2
const hasChinese = /[\u4e00-\u9fff]/.test('Hello 世界');
// true

密碼強度(至少8碼,含大小寫和數字)

1
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$
  • (?=.*[a-z]):至少一個小寫字母
  • (?=.*[A-Z]):至少一個大寫字母
  • (?=.*\d):至少一個數字
  • .{8,}:總長度至少 8 碼

參考資料