5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonで正規表現

Last updated at Posted at 2019-06-18

pythonで正規表現使うときの為の自分用メモです

種類と用途

re.match(正規表現パターン, 対象文字列):
普通の正規表現サーチ。指定範囲の1部を()で囲んで呼べるのが便利。

re.search(正規表現パターン, 対象文字列):
位置関係なしに指定パターンが出てくるか探してくれる。1つ見つけたら終わりにするのでありなし確認に使う。NGワード探しとかに使うと短く書けて便利。

re.findall(正規表現パターン, 対象文字列):
位置関係なしに指定パターンに該当する文字列を探して見つけた分を全部listにして返してくれる。何回出てくるか分からないときに使うと便利。

re.sub(正規表現パターン, 置き換える文字列, 対象文字列):
置き換えに使う。

返り値の違い

python
import re
result = re.match('([a-z]+)([0-9]*)', 入力文字列)
result = re.search('([a-z]+)([0-9]*)', 入力文字列)
result = re.findall('([a-z]+)([0-9]*)', 入力文字列)

上記のパターンで正規表現サーチをかけた返り値をresultに入れた場合に結果をどうやって取り出すか一覧にしてみました。re.match()、re.search()はオブジェクトが返ってきてresult[0]、result.group()、result.group[0]で該当文字列全体、()で囲んでグループを指定してあればresult[k]またはresult.group[k]でk番目のグループの文字列が受け取れるようです。

re.findall()はresultがlistなのでこっちは分かりやすいですね。
image.png

パターンの書き方

文字 説明 マッチする例
. 任意の文字
[0-9] 任意の数字 1, 2, 3, 9, 0
[^0-9] 数字以外 a, う, オ, -, z
[a-z] 任意のアルファベット a, e, h, t, z
\s 任意の空白文字 \t, \n, \r, \f, \v
\w 任意の英数字 a, u, R, 0, -

繰り返しの書き方

文字 説明
* 0回以上の繰り返し (できるだけ長く)
*? 0回以上の繰り返し (できるだけ短く)
+ 1回以上の繰り返し (できるだけ長く)
+? 1回以上の繰り返し (できるだけ短く)
{m} m回繰り返し
{m, n} m~n回繰り返し

多数回実行するときは先にcompileする

python
textList = ['hoge', 'hoge12', '123hoge', 'hoge123hoge', 'fuga_12345', '123_fuga_456', 'fuga123']
for text in textList:
    result = re.match('.*?[0-9]+', text)

複数回処理するなら下のように1度compileしてから実行した方が早い。

python
repattern = re.compile('.*?[0-9]+')
textList = ['hoge', 'hoge12', '123hoge', 'hoge123hoge', 'fuga_12345', '123_fuga_456', 'fuga123']
for text in textList:
    result = repattern.match(text)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?