正規表現基本チートシート
正規表現(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 |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches 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 |
注記
- 文字クラス [ ] の中では多くのトークンが特殊な意味を失います。例えば [ ] 内の . は単なるドットに一致します。
- バックスラッシュ(\)はエスケープ文字で、特殊トークンをリテラル文字に、その逆も可能にします。
- エンジンによって異なります。Python、JavaScript、PCRE、Golang は多くのトークンを共有しますが、フラグや先読みの対応は異なります。
よくある質問
- ドット(.)は何に一致しますか?
- 既定では改行以外の任意の 1 文字に一致します。文字通りのドットに一致させるには \. のようにエスケープします。
- * と + の違いは?
- * は直前のトークンに 0 回以上一致するため 'ab*' は 'a' にも一致します。+ は 1 回以上必要で、'ab' には一致しますが 'a' だけでは一致しません。
- 数字や単語の文字はどう表しますか?
- \d は任意の数字(0-9)、\w は任意の単語文字(英数字とアンダースコア)に一致します。その否定は \D と \W です。
- ^ と $ は何をしますか?
- ^ は文字列や行の先頭に、 $ は末尾に一致を固定します。 ^pattern$ を合わせると文字列全体に一致させられます。