■ はじめに
https://dk521123.hatenablog.com/entry/2019/09/01/000000
の続き。 今回は、より実践的なサンプル集。
目次
【1】パターンと一致しているファイル名かどうか判定 【2】JDBCの各パーツの抽出 【3】ファイル名からファイル日付を抽出 補足1:(?P<name>...) について 補足2:スクレイピングでの利用
【1】パターンと一致しているファイル名かどうか判定
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
【2】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
【3】ファイル名からファイル日付を抽出
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