Pythonで文字列が特定のパターンに一致するか判定(正規表現, re.match, re.search, re.fullmatch)
この記事では、Pythonの正規表現モジュールreを使って、文字列が特定のパターンに一致するかを判定する方法を解説します。re.match、re.search、re.fullmatchの3つの関数について、それぞれの特徴と使い分けを例を交えて説明します。
目次
正規表現とは?
正規表現とは、文字列のパターンを表現するための言語です。特定の文字列が含まれているか、特定の形式で書かれているかを効率的にチェックできます。Pythonでは`re`モジュールを使用します。
import re
# 簡単な例: 'hello'という文字列にマッチするか確認
pattern = 'hello'
string = 'hello world'
if re.search(pattern, string):
print('マッチしました')
else:
print('マッチしませんでした')
上記は`re.search`関数を使った例です。他にも`re.match`、`re.fullmatch`関数などがあります。それぞれ用途が異なるので、注意して使い分ける必要があります。
- メタ文字:. * + ? { } [ ] \ | ( ) $ ^ など、特別な意味を持つ文字
- 文字クラス:[abc] a, b, c のいずれか1文字
- アンカー:^ 文字列の先頭、$ 文字列の末尾
re.match関数
文字列の先頭からパターンにマッチするか判定します。マッチしない場合はNoneを返します。
import re
pattern = '^hello'
string1 = 'hello world'
string2 = 'world hello'
match1 = re.match(pattern, string1)
match2 = re.match(pattern, string2)
print(match1) # <re.Match object; span=(0, 5), match='hello'>
print(match2) # None
string1は先頭が'hello'なのでマッチしますが、string2はマッチしません。
import re
# グループ化
pattern = r'(\d{3})-(\d{4})'
string = '123-4567'
match = re.match(pattern, string)
if match:
print(match.group(0)) # 123-4567
print(match.group(1)) # 123
print(match.group(2)) # 4567
re.search関数
文字列の任意の位置でパターンにマッチするか判定します。マッチした最初の部分にマッチオブジェクトを返します。マッチしない場合はNoneを返します。
import re
pattern = 'world'
string1 = 'hello world'
string2 = 'world hello'
match1 = re.search(pattern, string1)
match2 = re.search(pattern, string2)
print(match1) # <re.Match object; span=(6, 11), match='world'>
print(match2) # <re.Match object; span=(0, 5), match='world'>
string1とstring2の両方で'world'が見つかるため、マッチします。
import re
pattern = r'a(b)c'
string = 'abc'
match = re.search(pattern, string)
if match:
print(match.group(1)) # b
re.fullmatch関数
文字列全体がパターンにマッチするか判定します。文字列全体がマッチする場合のみマッチオブジェクトを返し、そうでない場合はNoneを返します。
import re
pattern = '^hello$' # ^と$で文字列全体を指定
string1 = 'hello'
string2 = 'hello world'
match1 = re.fullmatch(pattern, string1)
match2 = re.fullmatch(pattern, string2)
print(match1) # <re.Match object; span=(0, 5), match='hello'>
print(match2) # None
string1は'hello'のみなのでマッチしますが、string2は'hello world'なのでマッチしません。
import re
# 数字のみの5文字
pattern = r'^\d{5}$'
string = '12345'
match = re.fullmatch(pattern, string)
if match:
print('マッチしました')
まとめ
re.match, re.search, re.fullmatch関数は、文字列と正規表現パターンを照合する際にそれぞれ異なる動作をします。文字列の先頭からのマッチ、任意の場所でのマッチ、文字列全体のマッチを必要とする状況に応じて適切な関数を選択しましょう。
- re.matchは文字列の先頭からのマッチを確認します。
- re.searchは文字列内の任意の場所でのマッチを確認します。
- re.fullmatchは文字列全体がパターンに一致するかどうかを確認します。
- 正規表現の構文は複雑なため、必要に応じてドキュメントを参照しましょう。
関連記事
- Pythonで文字列を検索(find, rfind, index, rindex)
- Pythonで文字列の先頭と末尾が特定の文字列か判定(startswith, endswith)
- Pythonで文字列の出現回数をカウント(count)
- Pythonで文字列を置換(replace, translate, re.sub)
- Pythonで文字列をフォーマット(format, f文字列 (Python 3.6以降), %演算子)
- Pythonで文字列がアルファベットかどうか判定(isalpha, isalnum)
- Pythonで文字列が数値かどうか判定(isdigit, isdecimal, isnumeric)
- Pythonで文字列の大文字・小文字を変換(upper, lower, capitalize, title, swapcase)
- Pythonで文字列の先頭・末尾の空白を削除(strip, lstrip, rstrip)
- Pythonで文字列をスライスで部分抽出