[Python]正規表現を使った文字列の抽出方法一覧(電話番号、メールアドレス、URLなど)

2022年1月8日土曜日

Python

Pythonで特定の文字列を検索・抽出する際の正規表現を一覧でご紹介します。

アイキャッチ

正規表現のパターンを定義

正規表現のパターンを事前に定義することで、同じ正規表現を何度も実装する必要がなくなります。

正規表現オブジェクト = re.compile(pattern)

re.compileの使用例

import re
target_1 = "このプログラムはPythonです。"
target_2 = "Pythonを学んでいます。"

# 正規表現のパターンを定義
pattern = re.compile(r"Python")

# 正規表現パターンに一致する最初の場所を検索
search_1 = pattern.search(target_1)
print(search_1)
# <_sre.SRE_Match object; span=(8, 14), match='Python'>

search_2 = pattern.search(target_2)
print(search_2)
# <_sre.SRE_Match object; span=(0, 6), match='Python'>

正規表現オブジェクトを生成することによって「r"Python"」を複数回記述する必要がなくなっています。
以降に、よく使う正規表現をご紹介します

電話番号を抽出

固定電話(4桁-2桁-4桁)と、携帯電話(3桁-4桁-4桁)の数字の文字列を抽出します。
携帯電話を抽出する正規表現は下記となります。
^[0-9]{3}-[0-9]{4}-[0-9]{4}$

  1. ^:文字列の先頭
  2. []:カッコ内の文字のどれかに一致
  3. {}:桁数を指定
  4. $: 文字列の末端
# 固定電話と携帯電話の正規表現パターンを定義
phone_number = "^[0-9]{4}-[0-9]{2}-[0-9]{4}$"
mobile_number = "^[0-9]{3}-[0-9]{4}-[0-9]{4}$"
phone_pattern = re.compile(phone_number)
mobile_pattern = re.compile(mobile_number)

target_list = ["090-1234-5678", "1234-56-7890", "090-1234-56789", "090-あ123-4567"]

for target in target_list:
    # 文字列の先頭から正規表現パターンに一致する範囲を抽出
    if phone_pattern.match(target) != None:
        print("固定電話:", target)
    elif mobile_pattern.match(target) != None:
        print("携帯電話:", target)
    else:
        print("電話番号ではありません:", target)

# 出力結果
# 携帯電話: 090-1234-5678
# 固定電話: 1234-56-7890
# どちらでもありません: 090-1234-56789
# どちらでもありません: 090-あ123-4567

メールアドレスを抽出

メールアドレスを抽出します。
メールアドレスを抽出する正規表現は下記となります。
^[0-9a-zA-Z_.+-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z-.]+$

# メールアドレスの正規表現パターンを定義
address = "^[0-9a-zA-Z_.+-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z-.]+$"
address_pattern = re.compile(address)

target_list = ["12_ab-XY@gmail.com", "34+ZA.56@yahoo.co.jp", "1234.54.co.jp"]

for target in target_list:
    # 文字列の先頭から正規表現パターンに一致する範囲を抽出
    if address_pattern.match(target) != None:
        print("メールアドレス:", target)
    else:
        print("メールアドレスではありません:", target)
# 出力結果
# メールアドレス: 12_ab-XY@gmail.com
# メールアドレス: 34+ZA.56@yahoo.co.jp
# メールアドレスではありません: 1234.54.co.jp

メールアドレスドメインを抽出

メールアドレスドメインを抽出します。
メールアドレスドメインを抽出する正規表現は下記となります。
@[\w.]+

# メールアドレスドメインの正規表現パターンを定義
address = "[0-9a-zA-Z_.+-]+@[0-9a-zA-Z-]+\.[0-9a-zA-Z-.]+"
address_domain = "@[\w.]+"

address_pattern = re.compile(address)
address_domain_pattern = re.compile(address_domain)

target_1 = "私のメールアドレスは12_ab-XY@gmail.comです。"

# 文字列からemailアドレスを取得
email = address_pattern.search(target_1)
print(email.group())
# 12_ab-XY@gmail.com

# emailアドレスからemailドメインを取得
domain = address_domain_pattern.search( email.group() )
print(domain.group())
# @gmail.com

URLを抽出

http://またはhttps://から始まるURLを抽出します。
URLを抽出する正規表現は下記となります。
https?://[\w/:%#\$&\?\(\)~\.=\+\-]+

# URLの正規表現パターンを定義
url = "https?://[\w/:%#\$&\?\(\)~\.=\+\-]+"
url_pattern = re.compile(url)

target_list = ["https://www.12-technology.com", "ftp://sample.com", "http://www.12-technology.com"]

for target in target_list:
    # 正規表現パターンに一致する最初の場所を検索
    if url_pattern.match(target) != None:
        print("URL:", target)
    else:
        print("URLではありません:", target)
# 出力結果
# URL: https://www.12-technology.com
# URLではありません: ftp://sample.com
# URL: http://www.12-technology.com

URLのホスト名を抽出

http://またはhttps://から始まるURLからホスト名を抽出します。
URLのホスト名を抽出する正規表現は下記となります。
https?://[^/]+/

# URLのホスト名の正規表現パターンを定義
url_host = "https?://[^/]+/"

url_host_pattern = re.compile(url_host)

target_1 = "サンプルURLはhttps://www.12-technology.com/2021/06/blog-post.htmlです。"

url_list = url_host_pattern.findall(target_1)
print(url_list)
# ['https://www.12-technology.com/']

AIで副業ならココから!

まずは無料会員登録

プロフィール

メーカーで研究開発を行う現役エンジニア
組み込み機器開発や機会学習モデル開発に従事しています

本ブログでは最新AI技術を中心にソースコード付きでご紹介します


Twitter

カテゴリ

このブログを検索

ブログ アーカイブ

TeDokology