LoginSignup
0
1

Pythonの検索処理 search match

Posted at

はじめに

Pythonの検索処理、re.searchre.matchについてまとめる。
re.searchはヒットした最初の文字列を抽出し、re.matchは先頭からヒットした文字列を抽出する違いがある。それぞれヒットした場合、re.Matchオブジェクトを返す。

目次

re.search

ヒットした最初の文字列を抽出する。

構文 意味
m = re.search(p,s) m:検索結果re.Matchオブジェクト
p:パターン文字列
r:検索文字列
search_sample.py
example='ABCDEF_abcdZ0123456789_Z0123456789_xyz_Z0123456789'

m = re.search(r'a.*Z',example)
#aから始まり、Zで終わる文字列の検索
print(m)
# <re.Match object; span=(7, 40), match='abcdZ0123456789_Z0123456789_xyz_Z'>

m = re.search(r'a.*?Z',example)
#aから始まり、最短のZで終わる文字列の検索
print(m)
# <re.Match object; span=(7, 12), match='abcdZ'>

同じパターンが含まれる場合、最短でヒットさせたい場合は?を使う。

戻る

re.match

先頭からヒットした文字列を抽出する。

構文 意味
m = re.match(p,s) m:検索結果re.Matchオブジェクト
p:パターン文字列
r:検索文字列
match_sample.py
example='ABCDEF_abcdZ0123456789_Z0123456789_xyz_Z0123456789'

m = re.match(r'a.*Z',example)
#aから始まり、Zで終わる文字列の検索
print(m)
# None 先頭からヒットしないのでNone

example='abcdZ0123456789_Z0123456789_xyz_Z0123456789'

m = re.match(r'a.*Z',example)
#aから始まり、Zで終わる文字列の検索
print(m)
# <re.Match object; span=(0, 33), match='abcdZ0123456789_Z0123456789_xyz_Z'>

戻る

re.Matchオブジェクト

検索結果はre.Matchオブジェクトに格納される。オブジェクトのパラメータは下記の通り。

rematch_sample.py
example='abcdefg_01234567890@xxx.yyy.com'

m = re.search(r'(a.*)(@)(.*)',example)

print(m)
# <re.Match object; span=(0, 31), match='abcdefg_01234567890@xxx.yyy.com'>

print(f'{m.start()=}')  # m.start()=0
print(f'{m.end()=}')    # m.end()=31
print(f'{m.span()=}')   # m.span()=(0, 31)
print(f'{m.groups()=}') # m.groups()=('abcdefg_01234567890', '@', 'xxx.yyy.com')
print(f'{m.group(0)=}') # m.group(0)='abcdefg_01234567890@xxx.yyy.com'
print(f'{m.group(1)=}') # m.group(1)='abcdefg_01234567890'
print(f'{m.group(2)=}') # m.group(2)='@'
print(f'{m.group(3)=}') # m.group(3)='xxx.yyy.com'

for i in m.groups():
	print(i)
# abcdefg_01234567890
# @
# xxx.yyy.com

re.Matchの詳細は下記参照。

戻る

0
1
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
0
1