🔍 Regex Tester
📐 工作原理與說明
用 new RegExp(表示式, 修飾符) 編譯後匹配:帶 g 時迴圈呼叫 exec 收集全部結果,遇到零寬匹配(match.index 等於 lastIndex)時手動把 lastIndex 加一以防死迴圈,匹配數超過 1000 條提前終止;明細列表最多展示前 100 條、高亮最多覆蓋前 500 條,引擎收集與複製上限為 1000 條;不帶 g 時只取首個匹配。統計:匹配數即收集條數,捕獲組數 = 首個匹配長度 − 1;端到端耗時 = 主執行緒 performance.now 起止差(含 Worker 建立、訊息傳遞與主執行緒排程,不是純正則引擎耗時),Worker 內的匹配計算耗時另列;單次測量受裝置與執行緒排程影響,不能直接作為表示式效能基準;表示式為空時不執行匹配並清零統計
正規表示式測試工具:匹配、提取與替換。
- 元字元:
.*+?^$[]()|\d\w\s。 - 標誌:g 全域性、i 忽略大小寫、m 多行、s 使
.匹配換行、u 啟用 Unicode。 - 用途:校驗格式、批次提取、文本替換。
- 風險:巢狀量詞(如
(a+)+)會引發災難性回溯,導致 CPU 耗盡。
Test and debug regular expressions with live matching; capture groups are listed per match.
/
/
🎯 匹配測試
🔄 替換功能
📚 常用正則
使用瀏覽器 JavaScript 正則引擎;結果與前端 RegExp 行為一致。
By default only the pattern and flags are shared. If enabled, the test text is encoded into the URL fragment; encoding is not encryption, so logs or credentials may be exposed and the link may remain in browser history or the clipboard.
History is stored locally. By default only the pattern, flags and result summary are saved; test text is not saved unless enabled. The CSV export first writes the current match list (# / match / groups / index), falling back to the history summary table when there are no matches.
輸入正則後將自動匹配...
高亮結果將顯示在這裡...
替換語法:
$& 匹配的文本
$1 第1個分組
$` 匹配前文本
$' 匹配後文本
替換結果將顯示在這裡...
📖 正則語法速查
| 語法 | 說明 | 示例 |
|---|---|---|
. | 匹配任意字元(除換行) | a.c 匹配 abc |
\d | 數字 [0-9] | \d+ 匹配 123 |
\w | 單詞字元 [a-zA-Z0-9_] | \w+ 匹配 hello_123 |
\s | 空白字元 | \s+ 匹配空格 |
^ | 行首 | ^Hello 匹配行首Hello |
$ | 行尾 | end$ 匹配行尾end |
* | 0次或多次 | a* 匹配 空、a、aaa |
+ | 1次或多次 | a+ 匹配 a、aaa |
? | 0次或1次 | colou?r 匹配 color/colour |
{n} | 恰好n次 | \d{3} 匹配 3位數字 |
{n,} | 至少n次 | \d{2,} 匹配 2位以上 |
{n,m} | n到m次 | \d{2,4} 匹配 2-4位 |
[abc] | 字元集 | [aeiou] 匹配母音 |
[^abc] | 排除字元集 | [^0-9] 匹配非數字 |
(abc) | 捕獲分組 | (\d+)-(\d+) 捕獲兩組 |
(?:abc) | 非捕獲分組 | (?:ab)+ 不捕獲 |
a|b | 或 | cat|dog 匹配cat或dog |
(?=abc) | 正向先行斷言 | \d(?=px) 後跟px的數字 |
(?!abc) | 負向先行斷言 | \d(?!px) 後不跟px的數字 |
📚 深度解析:正規表示式測試器
💡 常見使用場景
- 即時測試正則匹配與捕獲組。
- 上線前先把正則放進真實樣本里試:確認既不會漏掉合法輸入,也不會誤匹配非法輸入,再寫進程式碼。
測試
`\d{3}-\d{4}` 匹配 `123-4567`,高亮並列出分組。
❓ 常見問題(FAQ)
- 如何全域性匹配?
- 加 `g` 標誌遍歷所有匹配。
- 為什麼匹配卡住了?
- 很可能是災難性回溯:巢狀量詞(如 (a+)+)在遇到長而不匹配的字串時,嘗試次數會指數級增長,導致 CPU 打滿。解決辦法是避免巢狀量詞、改用更具體的字元類,或用原子組/獨佔量詞(視引擎支援)。使用者可控的正則應設超時保護。
Formula & Standard References
| Item | Formula / Note | Source / Standard |
|---|---|---|
| Character classes | \d \w \s with negations; [] for custom sets | ECMA-262 / POSIX ERE |
| Quantifiers | * + ? and {n,m}; greedy by default | ECMA-262 |
| Backtracking risk | JS has no atomic groups; avoid nested quantifiers | OWASP ReDoS guidance |
⚠️ 使用說明與注意事項
- 本工具純前端執行,資料不會上傳到伺服器
- 建議在主流瀏覽器(Chrome/Safari/Firefox/Edge)中使用
- 計算結果僅供參考,請以實際應用場景為準