正規表示式基礎速查

正規表示式(regex)是用來匹配文本的模式。每個符號稱為一個記號,會改變匹配行為。下面速查列出最常用的記號,附通俗解釋和可複製測試的範例。

更新日期:

記號含義範例
.Matches any single character except newline.a.c matches abc, a c
*Matches the preceding token zero or more times.ab* matches a, abb
+Matches the preceding token one or more times.ab+ matches ab, abb
?Makes the preceding token optional (zero or one).colou?r matches color, colour
[]Character set: matches any one character inside.[aeiou] matches any vowel
[^]Negated set: matches any character NOT inside.[^0-9] matches any non-digit
\dMatches any digit (0-9).\d+ matches 42, 007
\wMatches any word character (a-z, A-Z, 0-9, _).\w+ matches hello_1
\sMatches any whitespace (space, tab, newline).a\sb matches a b
^Anchors the match to the start of a line/string.^Hello matches start of string
$Anchors the match to the end of a line/string.world$ matches end of string
|Alternation: matches the pattern on either side.cat|dog matches cat or dog
()Groups a sub-pattern (and captures it).(ab)+ matches ab, abab
{n,m}Quantifier: match the preceding token n to m times.a{2,4} matches aa, aaaa
(?i)Inline flag: makes the pattern case-insensitive.(?i)hello matches HELLO

說明

常見問題

點號(.)匹配什麼?
預設點號匹配除換行符外的任意單一字元。要匹配字面點號需用反斜線轉義為 \.
* 和 + 有什麼差別?
星號 * 匹配前面記號零次或多次,故 'ab*' 也能匹配 'a'。加號 + 至少一次,匹配 'ab' 但不匹配單獨的 'a'。
如何匹配數字或單字字元?
用 \d 匹配任意數字(0-9),用 \w 匹配任意單字字元(字母、數字、底線)。其反向為 \D 與 \W。
^ 和 $ 有什麼用?
^ 把匹配錨定到字串或行首;$ 錨定到末尾。合起來 ^pattern$ 強制整串匹配。