正規表現(Regular Expressions、略してRegex)は、特定のパターンにマッチする文字列を検索、抽出、変換するための表現方法です。たとえば、 など、さまざまな用途で使われます。 Pythonでは ※まだPythonを手に入れていない方は、こちらを参照していただけたらと思います。 Pythonで正規表現を使うには、まず re モジュールをインポートします。 re.search() は、文字列内で最初にマッチする部分を検索します。 re.findall() を使うと、すべての一致をリストで取得できます。 re.sub() を使うと、マッチする部分を置換できます。 僕は、ファイルパスを変える時とかに使いっていました。C#では。
そのため、Python版もと思い、記載しています。 📂 入力例 📂 出力例 📝 実装コード Pythonの re モジュールを使うことで、文字列の検索・置換・抽出が簡単にできます。 さらに、実務でよくあるファイル名の変換やコピー処理も簡単に行えます。
1. はじめに
正規表現とは?
re
モジュールを使用することで、簡単に正規表現を扱えます。本記事では、基本から応用までの使い方を詳しく解説します!2. reモジュールの基本
2.1 reモジュールのインポート
import re
2.2 文字列の検索(re.search())
text = "Hello, my email is example@email.com"
match = re.search(r'\w+@\w+\.\w+', text)
if match:
print("メールアドレスが見つかりました:", match.group())
2.3 すべての一致を取得(re.findall())
text = "Emails: test@example.com, support@company.org"
emails = re.findall(r'\w+@\w+\.\w+', text)
print("見つかったメールアドレス:", emails)
2.4 文字列の置換(re.sub())
text = "Hello 123, this is a test 456."
new_text = re.sub(r'\d+', '[NUMBER]', text)
print(new_text)
# Hello [NUMBER], this is a test [NUMBER].
3. 正規表現の基本パターン
パターン
説明
例
.
任意の1文字
a.c
→ abc
, axc
にマッチ
\d
数字(0-9)
\d+
→ 123
, 456
にマッチ
\w
単語構成文字
\w+
→ hello
, Python_3
にマッチ
\s
空白文字
\s+
→ ' '
や ' '
にマッチ
^
文字列の先頭
^Hello
→ Hello world
にマッチ
$
文字列の末尾
world$
→ Hello world
にマッチ 4. 応用例:日付パスの変更とファイルコピー
📌 シナリオ
/logs/2024-03-11/report1.txt
/logs/2024-03-11/report2.txt
/logs/2025-03-11/report1.txt
/logs/2025-03-11/report2.txt
import re
import os
import shutil
old_date = "2024-03-11"
new_date = "2025-03-11"
file_paths = [
f"/logs/{old_date}/report1.txt",
f"/logs/{old_date}/report2.txt"
]
for old_path in file_paths:
new_path = re.sub(rf'/{old_date}/', f'/{new_date}/', old_path)
new_dir = os.path.dirname(new_path)
os.makedirs(new_dir, exist_ok=True)
shutil.copy(old_path, new_path)
print(f"Copied: {old_path} → {new_path}")
5. まとめ