1
0

Pythonで「文字列の先頭位置からパターンとマッチするか調べる(Pattern.match)」の動作を確認してみた

Posted at

概要

Pythonで「文字列の先頭位置からパターンとマッチするか調べる(Pattern.match)」の動作を確認してみました。
以下のページを参考にしました。

実装

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

sample.py
import re

def checkMatch(msg, pat):
    pattern = re.compile(pat)
    result = pattern.match(msg)
    if result :
        print(result.group(0))
    else :
        print('Don\'t matched')

checkMatch('東京都港区赤坂', r'東京.')
checkMatch('東京都港区赤坂', r'港.')

import re

def checkMatch(msg, pattern, start, end):
    result = pattern.match(msg, start, end)
    if result :
        print(result.group(0))
    else :
        print('Don\'t matched')

msg = '東京都港区赤坂'
pattern = re.compile(r'港区')

checkMatch(msg, pattern, 0, 7)
checkMatch(msg, pattern, 3, 7)

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

$ python3 sample.py 
東京都
Don't matched
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