Python re ライブラリ完全ガイド
Python 標準ライブラリの re は、正規表現(Regular Expressions)を扱うための強力なツールです。文字列の検索、置換、抽出、パターンマッチングなど、テキスト処理を行う際に非常に役立ちます。本記事では、re ライブラリの基本概念から実践的な使用例までを詳しく解説します。
1. re ライブラリの概要
reは、正規表現を使用して文字列を処理するための標準ライブラリです。- テキストデータの検索、抽出、置換、分割などが可能です。
- Webスクレイピング、ログ解析、データクレンジングなど幅広く活用されます。
インストール方法
re は Python の標準ライブラリなので、追加のインストールは不要です。
import re
import re
text = "Pythonで正規表現を学ぶ"
pattern = "正規表現"
match = re.search(pattern, text)
if match:
print("一致する文字列を発見:", match.group())
import re
text = "Python123"
pattern = r"^Python[0-9]+$"
if re.match(pattern, text):
print("パターンに一致しました!")
else:
print("一致しませんでした。")
import re
text = "メール: user1@example.com, user2@example.net"
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
emails = re.findall(pattern, text)
print("見つかったメールアドレス:", emails)
import re
text = "Hello 123, this is a test 456."
pattern = r"\d+"
# 数字を * に置換
new_text = re.sub(pattern, "*", text)
print("置換後のテキスト:", new_text)
import re
text = "apple, banana; cherry|grape"
pattern = r"[,;|]"
words = re.split(pattern, text)
print("分割結果:", words)