【Python】Python ~ 基本編 / 正規表現あれこれ ~

■ はじめに

https://dk521123.hatenablog.com/entry/2019/09/01/000000

の続き。

今回は、より実践的なサンプル集。

目次

【1】電話番号を判定
【2】名前から姓名を抽出
【3】パターンと一致しているファイル名かどうか判定
【4】JDBCの各パーツの抽出
【5】ファイル名からファイル日付を抽出
 補足1:(?P<name>...) について
 補足2:スクレイピングでの利用

【1】電話番号を判定

import re

match_result = re.match(
  r'(\d+)-(\d+)-(\d+)', '03-1234-5678')
print(f'match_result(0) = {match_result.group(0)}')
print(f'match_result(1) = {match_result.group(1)}')
print(f'match_result(2) = {match_result.group(2)}')
print(f'match_result(3) = {match_result.group(3)}')

出力結果

match_result(0) = 03-1234-5678
match_result(1) = 03
match_result(2) = 1234
match_result(3) = 5678

【2】名前から姓名を抽出

import re

match_result = re.match(
  r'(?P<first_name>\w+) (?P<last_name>\w+)',
  'Steve jobs')
print(f'match_result(0) = {match_result.group(0)}')
first_name = match_result.group('first_name')
print(f'match_result(first_name) = {first_name}')
last_name = match_result.group('last_name')
print(f'match_result(last_name) = {last_name}')

出力結果

match_result(0) = Steve jobs
match_result(first_name) = Steve
match_result(last_name) = jobs

【3】パターンと一致しているファイル名かどうか判定

import re

# re.search("パターン", "対象文字列")
if (re.search("hello[_-]\d+.csv", "hello_20201120.csv")):
  print("Hit")
else:
  print("...")

if (re.search("hello[_-]\d+.csv", "hello-20201120.csv")):
  print("Hit")
else:
  print("...")

if (re.search("hello[_-]\d+.csv", "hello-20201120.txt")):
  print("Hit")
else:
  print("...")

# 1文字(s)がある場合とない場合があるとき
if (re.search("Word[s]?_\d+.csv", "Word_20201120.csv")):
  print("Hit")
else:
  print("...")

if (re.search("Word[s]?_\d+.csv", "Words_20201120.csv")):
  print("Hit")
else:
  print("...")

出力結果

Hit
Hit
...
Hit
Hit

【4】JDBCの各パーツの抽出

import re

connection_url = "jdbc:redshift://localhost:5432/sample_db"

results = re.findall(r'jdbc:(\S+)://(\S+):(\d+)/(\S+)$', connection_url)

print(results)
print(results[0][0])
print(results[0][1])
print(results[0][2])
print(results[0][3])

出力結果

[('redshift', 'localhost', '5432', 'sample_db')]
redshift
localhost
5432
sample_db

【5】ファイル名からファイル日付を抽出

import re


sample_file_name = "data_file_20220105.csv"

REGEX_DEMO = re.compile(r"_(?P<file_date>[\d]+).csv")
match = REGEX_DEMO.search(sample_file_name)
if match:
    file_date = match.group("file_date")
    print(f"file_date is {file_date}")
else:
    print("not match...")

補足1:(?P...) について

* 以下のAPI仕様の「(?P<name>...)」を参照。

https://docs.python.org/ja/3/library/re.html

補足2:スクレイピングでの利用

* 以下の動画で、スクレイピングで利用している

https://youtu.be/OEvD9gSWf20?t=1288

関連記事

Python ~ 基本編 / 正規表現
https://dk521123.hatenablog.com/entry/2019/09/01/000000
Python 基本編 / 文字列
https://dk521123.hatenablog.com/entry/2019/10/12/075251
正規表現 全般
https://dk521123.hatenablog.com/entry/2011/09/10/235712