Python の正規表現の基礎

Python の基礎

日付:2025年2月18日

Python における正規表現の基本的な使い方やパターンの構築方法について解説します。文字列の検索や置換を効率的に行うためのテクニックを紹介します。

目 次

はじめに

Python の 正規表現(Regular Expressions, RegExp) は、re モジュールを使って文字列のパターンマッチングや置換を効率的に行うための強力なツールです。

本記事では、Python の re モジュールを使った正規表現の基本構文や実践的な使用例を解説します。

1. 正規表現の基本

Python で正規表現を扱うには re モジュールをインポートする必要があります。

PYTHON
import re

1.1 re.search() - 部分一致を検索

PYTHON
import re text = "Hello, my name is Alice." pattern = r"Alice" match = re.search(pattern, text) if match: print("見つかりました:", match.group())

re.search()文字列の中から最初にマッチする部分を検索 します。

1.2 re.match() - 先頭から一致を検索

PYTHON
import re text = "Alice in Wonderland" pattern = r"Alice" match = re.match(pattern, text) if match: print("先頭でマッチしました:", match.group())

re.match()文字列の先頭にマッチする場合のみ成功 します。

2. 正規表現のフラグ

Python の re モジュールには、検索の挙動を制御する フラグ(オプション) があります。

フラグ説明
re.IGNORECASE (re.I)大文字・小文字を区別しない
re.MULTILINE (re.M)複数行検索を有効にする
re.DOTALL (re.S). を改行 \n にもマッチさせる

例:大文字・小文字を区別しない検索

PYTHON
import re text = "Hello World" pattern = r"hello" match = re.search(pattern, text, re.IGNORECASE) print(match.group()) # "Hello"

3. 正規表現のパターン

3.1 文字クラス

パターン説明
\d数字(0-9)
\w英数字(a-z, A-Z, 0-9, _)
\s空白(スペース、タブ、改行)
.任意の 1 文字
PYTHON
import re pattern = r"\d+" text = "Age: 25" match = re.search(pattern, text) print(match.group()) # "25"

3.2 繰り返し(量指定子)

記号説明
*0 回以上の繰り返し
+1 回以上の繰り返し
?0 回または 1 回の出現
{n}n 回の繰り返し
{n,}n 回以上の繰り返し
{n,m}n 回以上 m 回以下の繰り返し
PYTHON
import re pattern = r"\d{2,4}" text = "2023" match = re.search(pattern, text) print(match.group()) # "2023"

4. 文字列の検索と置換

4.1 re.findall() - すべての一致を取得

PYTHON
import re text = "Python 3.9, Python 3.10, Python 3.11" pattern = r"Python \d+\.\d+" results = re.findall(pattern, text) print(results) # ['Python 3.9', 'Python 3.10', 'Python 3.11']

4.2 re.sub() - 文字列の置換

PYTHON
import re text = "Hello, Alice!" pattern = r"Alice" new_text = re.sub(pattern, "Bob", text) print(new_text) # "Hello, Bob!"

5. まとめ

Python の正規表現のポイント

  • re.search()部分一致を検索
  • re.match()先頭から一致を検索
  • re.findall()すべての一致を取得
  • re.sub()文字列を置換
  • フラグ(re.IGNORECASE, re.MULTILINE)を活用すると検索範囲を広げられる。

Python の正規表現を活用すれば、データ処理や文字列操作が格段に楽になります。