LoginSignup
5
8

More than 3 years have passed since last update.

製薬企業研究者がPythonにおける正規表現についてまとめてみた

Posted at

はじめに

ここでは、Pythonにおける正規表現の基本について解説します。

主な正規表現

import re

m1 = re.match(r'ab*', 'a') # 直前の文字(b)の0回以上の繰り返し
if m1:
    print(m1.group(0))
else:
    print('Not match')

m2 = re.match(r'ab+', 'a') # 直前の文字(b)の1回以上の繰り返し
if m2:
    print(m2.group(0))
else:
    print('Not match')

m3 = re.match(r'ab?', 'abb') # 直前の文字(b)の0回または1回の繰り返し
if m3:
    print(m3.group(0))
else:
    print('Not match')

m4 = re.match(r'ab$', 'abb') # 文字列の末尾と合致するか
if m4:
    print(m4.group(0))
else:
    print('Not match')

m5 = re.match(r'[a-e]', 'f') # []内のいずれかの文字(a, b, c, d, e)とマッチするか
if m5:
    print(m5.group(0))
else:
    print('Not match')

正規表現の関数

import re

# 先頭からマッチするか
match = re.match(r'\d+-*\d+$', '012-3456')
print(match.group(0)) # '012-3456'

# 途中でマッチするか
search = re.search(r'\d{3}', '012-3456')
print(search.group(0)) # '012'

# マッチするパターンを全て列挙
print(re.findall(r'\d{3}', '012-3456')) # ['012', '345']

# 指定したパターンの区切り文字で分割
print(re.split(r'[,、]', '1,2、さん')) # ['1', '2', 'さん']

# 指定したパターンの文字を別のパターンに変換
print(re.sub(r'(\d),(\d)', r'\2,\1', '1,2、さん')) # 2,1、さん

まとめ

ここでは、Pythonにおける正規表現の基本について解説しました。
特定の文字列パターンと合致させたい場合は正規表現を利用すると便利です。

参考資料・リンク

プログラミング言語Pythonとは?AIや機械学習に使える?

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8