TL
Tool Lab
💰捐贈
💰捐贈

正規表達式參考

正規表達式語法快速參考指南,包括字元類、錨點、量詞、分組、旗標和常用模式。

字元類

.Any character except newline
\wWord character [a-zA-Z0-9_]
\WNon-word character
\dDigit [0-9]
\DNon-digit
\sWhitespace (space, tab, newline)
\SNon-whitespace
[abc]Character class — a, b, or c
[^abc]Negated class — not a, b, or c
[a-z]Range — any lowercase letter
[a-zA-Z0-9]Alphanumeric characters

錨點

^Start of string (or line with multiline)
$End of string (or line with multiline)
\bWord boundary
\BNon-word boundary
\AStart of string (not multiline)
\ZEnd of string (not multiline)

量詞

*Zero or more (greedy)
+One or more (greedy)
?Zero or one (greedy)
{n}Exactly n times
{n,}n or more times
{n,m}Between n and m times
*?Zero or more (lazy/non-greedy)
+?One or more (lazy/non-greedy)
??Zero or one (lazy/non-greedy)

分組與選擇

(abc)Capture group
(?:abc)Non-capturing group
(?P<name>abc)Named capture group
a|bAlternation — a or b
(?=abc)Positive lookahead
(?!abc)Negative lookahead
(?<=abc)Positive lookbehind
(?<!abc)Negative lookbehind

轉義與特殊字元

\nNewline
\tTab
\rCarriage return
\0Null character
\uXXXXUnicode character (hex)
\.Literal dot (escaped)
\\Literal backslash

旗標

gGlobal — find all matches
iCase-insensitive
mMultiline — ^ and $ match line start/end
sDotall — . matches newline
uUnicode — treat pattern as Unicode
ySticky — match from lastIndex

常用模式

^[\w.-]+@[\w.-]+\.\w{2,}$Email address
https?://[\w./%-]+URL (basic)
^\d{1,3}(\.\d{1,3}){3}$IPv4 address
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$Hex color
^\d{4}-\d{2}-\d{2}$ISO date (YYYY-MM-DD)
^[+]?[\d\s()-]{7,15}$Phone number (basic)
^(?=.*[A-Z])(?=.*\d).{8,}$Password: 8+ chars, 1 uppercase, 1 digit

關於本工具

正規表達式是描述字串模式的強大語言。本參考涵蓋最常用的語法和模式。

按類別分節整理,可使用搜尋框通過關鍵詞快速過濾模式。

使用方法

  1. 瀏覽各節查找所需語法。
  2. 使用搜尋框按關鍵詞過濾。
  3. 點擊任意模式將其複製到剪貼簿。
  4. 在正規表達式測試工具中測試模式。

使用情境

適用於表單驗證、字串解析、日誌分析、尋找取代等各種程式設計任務。

常見問題

  • 正規表達式在所有語言中都適用嗎?大多數語言支援正規表達式,但語法略有差異。JavaScript、Python、Java等主要語言大多遵循PCRE相容語法。
  • 如何進行大小寫不敏感匹配?在模式後新增i旗標。例如:/pattern/i
  • 貪婪量詞和懶惰量詞有什麼區別?貪婪量詞(*, +, ?)盡可能多地匹配,懶惰量詞(*?, +?, ??)盡可能少地匹配。