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

■ はじめに

正規表現(Regular expression)を使いそうなので、予習。

目次

【1】Python の正規表現
【2】サンプル
 例1:文字列判定
 例2:文字列抽出
 例3:文字列抽出・複数版
 例3の別解
 例4:文字列置換

【1】Python正規表現

re モジュールを使う

【2】サンプル

以下の基本的な処理を行うサンプル。

例1:文字列判定
例2:文字列抽出
例3:文字列抽出・複数版
例3の別解

例1:文字列判定

import re

# re.search("パターン", "対象文字列")
if (re.search("Hello", "Hello World!!")):
  print("Hit")
else:
  print("...")

if (re.search("Hello w", "Hello World!!")):
  print("Hit")
else:
  print("...")

# 大文字・小文字を区別しない
if (re.search("Hello w", "Hello World!!", re.IGNORECASE)):
  print("Hit")
else:
  print("...")

# 別対応
if (re.search("Hello [wW]", "Hello World!!")):
  print("Hit")
else:
  print("...")

出力結果

Hit
...
Hit
Hit

例2:文字列抽出

import re

def main():
    content = r'hello_world_20191012.csv'
    pattern = r'\d{8}'
    
    regularExpresion = re.compile(pattern)
    matching = regularExpresion.search(content)

    print("Result:" + matching.group())

if __name__ == '__main__':
    main()

出力結果

Result:20191012

例3:文字列抽出・複数版

import re

target_string = "hello_world_from_20201110_to_20201111.csv"

pattern = re.compile("[0-9]{4}[0-9]{2}[0-9]{2}")
matching_list = pattern.findall(target_string)
for matching in matching_list:
  print(matching)

print("Done")

出力結果

20201110
20201111
Done

例3の別解

import re

target_string = "hello_world_20201110_121212121.csv"

pattern = re.compile("([0-9]{4}[0-9]{2}[0-9]{2})_(\d+)")
matching_list = pattern.findall(target_string)
for matching in matching_list:
  print("{}, {}".format(matching[0], matching[1]))

print("Done")

出力結果

20201110, 121212121
Done

例4:文字列置換

import re

input = 'a1[shape="ellipse"];'

print(re.sub('a1\[.*\];', 'a1[shape="box" color="red"];', input))
# a1[shape="box" color="red"];

https://note.nkmk.me/python-str-replace-translate-re-sub/

参考文献

https://hibiki-press.tech/learn_prog/python/regex_pattern/1099
https://uxmilk.jp/41416
https://qiita.com/luohao0404/items/7135b2b96f9b0b196bf3
http://sarchitect.net/15225
https://codeday.me/jp/qa/20190523/887032.html
https://qiita.com/wanwanland/items/ce272419dde2f95cdabc
https://qiita.com/kaeruair/items/747518c116c85a88ee21 https://hibiki-press.tech/learn_prog/python/regular_expression/1097
http://trelab.info/python/python-%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%8F%BE%E3%81%A7url%E3%81%AE%E4%B8%80%E8%87%B4%E3%83%81%E3%82%A7%E3%83%83%E3%82%AF%E3%80%81%E6%8A%BD%E5%87%BA%E3%82%92%E8%A1%8C%E3%81%86/

関連記事

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