1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで「パターンにマッチしたすべてのマッチオブジェクトを取得する(Pattern.finditer)」の動作を確認してみた

Posted at

概要

Pythonで「パターンにマッチしたすべてのマッチオブジェクトを取得する(Pattern.finditer)」の動作を確認してみました。
以下のページを参考にしました。

実装

以下のファイルを作成しました。

sample.py
import re

msg = 'MA-52, JO-72, PP-45'
pattern = re.compile(r'[A-Z]{2}-[0-9]{2}')

result = pattern.finditer(msg)

for m in result:
    print(m.group())

import re

msg = 'MA-52, JO-72, PP-45'
pattern = re.compile(r'([A-Z]{2})-([0-9]{2})')

result = pattern.finditer(msg)

for m in result:
    print('Match:' + m.group(0))
    print('Group1:' + m.group(1))
    print('Group2:' + m.group(2))

import re

msg = 'Sample'
pattern = re.compile(r'[A-Z]{2}-[0-9]{2}')

result = pattern.finditer(msg)
m = None

for m in result:
    print(m.group())

if m is None:
    print('Don\'t matched')

以下のコマンドを実行しました。

$ python3 sample.py 
MA-52
JO-72
PP-45
Match:MA-52
Group1:MA
Group2:52
Match:JO-72
Group1:JO
Group2:72
Match:PP-45
Group1:PP
Group2:45
Don't matched

まとめ

何かの役に立てばと。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?