LoginSignup
23
16

More than 5 years have passed since last update.

【python】re.match より re.search を使おう

Posted at

TL;DR

re.match は文字列の先頭からしかマッチしない。

  • 部分一致したい -> re.search
  • 全体一致したい -> re.fullmatch

fullmatch が全体一致なので match は部分一致かな?と適当に使うと痛い目を見るので注意が必要です。

python の正規表現

公式: https://docs.python.jp/3/library/re.html#re.search

  • re.search: 文字列の部分のマッチ
  • re.match: 文字列の先頭からのマッチ
  • re.fullmatch: 文字列の全体のマッチ

となっています。
具体例としては以下のようになります。

text aaa aaaB Baaa BBB
re.search(r'aaa', text)
re.match(r'aaa', text)
re.fullmatch(r'aaa', text)

文字列の最初からのみの一致って私には少し特殊に思えるのですがどうなのでしょうか。

23
16
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
23
16