Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Python| Pythonで正規表現

概要

Python正規表現

内容

reライブラリで正規表現を利用します.
下記に、正規表現のマッチングと置換の例を記します。

サンプルコード

regexp.py

# -*- coding: utf-8 -*-
import re

class YmdRegexp:
  def ymd_matcher(self, value):
    return True if self._get_ymd_pattern().match(value) else False

  def ymd_replace(self, value, after):
    return self._get_ymd_pattern().sub(value, after)

  def _get_ymd_pattern(self):
    return re.compile('^(\d){4}\/(\d){2}\/(\d){2}$')

year_regexp = YmdRegexp()
print year_regexp.ymd_matcher("2012/04/02")
print year_regexp.ymd_matcher("2012/0402")
print year_regexp.ymd_matcher("2012/04/2")

print year_regexp.ymd_replace("2012/04/02", "hoge")

出力

$python regexp.py
True
False
False
hoge