正規表現とは
正規表現(regular expression)は、文字列のパターンを記述する特殊な記法です。文字列の検索、マッチング、置換など多くの場面で使えます。
python
import re # 正規表現モジュール基本的なパターン
| パターン | 説明 | 例 |
|:---:|:---|:---|
| . | 任意の1文字(改行以外) | a.c → abc, axc |
| * | 直前の文字の0回以上の繰り返し | ab*c → ac, abc, abbc |
| + | 直前の文字の1回以上の繰り返し | ab+c → abc, abbc |
| ? | 直前の文字の0回または1回 | ab?c → ac, abc |
| ^ | 文字列の先頭 | ^Hello |
| $ | 文字列の末尾 | World$ |
| \d | 数字 [0-9] | \d{3} → 123 |
| \w | 英数字とアンダースコア | \w+ |
| \s | 空白文字(スペース・タブ・改行) | \s+ |
| [...] | 文字クラス | [aeiou] |
| [^...] | 否定文字クラス | [^0-9] |
| {n} | ちょうどn回の繰り返し | \d{4} → 2024 |
| {n,m} | n〜m回の繰り返し | \d{2,4} |
主な関数
re.match() - 先頭からマッチ
python
import re# 先頭からのマッチm = re.match(r"Hello", "Hello, World!")if m: print("マッチしました:", m.group()) # Hello# 先頭でなければマッチしないm = re.match(r"World", "Hello, World!")print(m) # Nonere.search() - 文字列全体を検索
python
import re# 文字列全体を検索m = re.search(r"World", "Hello, World!")if m: print("見つかりました:", m.group()) # World print("位置:", m.start(), "-", m.end()) # 7 - 12re.findall() - 全てのマッチを取得
python
import re# メールアドレスを全て抽出text = "お問い合わせ: info@example.com, support@test.jp"emails = re.findall(r"[w.]+@[w.]+", text)print(emails) # ["info@example.com", "support@test.jp"]# 数字を全て取得text = "1月の売上は100万円、2月は150万円です。"numbers = re.findall(r"d+", text)print(numbers) # ["1", "100", "2", "150"]re.sub() - 置換
python
import re# 数字を * に置換text = "電話: 090-1234-5678"masked = re.sub(r"d", "*", text)print(masked) # 電話: ***-****-****# HTMLタグを除去html = "<h1>タイトル</h1><p>本文</p>"clean = re.sub(r"<[^>]+>", "", html)print(clean) # タイトル本文re.split() - 分割
python
import re# 複数の区切り文字で分割text = "apple,banana;cherry orange"parts = re.split(r"[,; ]+", text)print(parts) # ["apple", "banana", "cherry", "orange"]グループ
括弧 () でグループを作ると、マッチした部分を取り出せます。
python
import re# 日付のパターン(YYYY-MM-DD)text = "誕生日は 2000-03-15 です。"m = re.search(r"(d{4})-(d{2})-(d{2})", text)if m: year, month, day = m.groups() print(f"年: {year}, 月: {month}, 日: {day}") # 年: 2000, 月: 03, 日: 15# 名前付きグループm = re.search(r"(?P<year>d{4})-(?P<month>d{2})-(?P<day>d{2})", text)if m: print(m.group("year")) # 2000コンパイル済みパターン
同じパターンを繰り返し使う場合は、コンパイルしておくと効率的です。
python
import re# パターンをコンパイルemail_pattern = re.compile(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}")emails = ["valid@example.com", "invalid-email", "another@test.jp"]for email in emails: if email_pattern.match(email): print(f"✓ {email}") else: print(f"✗ {email}")練習: 電話番号の検証
日本の電話番号(固定電話・携帯電話)にマッチするパターンを作成してください。
例: 03-1234-5678, 090-1234-5678, 0120-123-456
練習: URLからドメインを抽出
URL文字列からドメイン名を抽出する関数 extract_domain(url) を定義してください。