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.search)」の動作を確認してみた

Posted at

概要

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

実装

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

sample.py
import re

msg = 'lemon, apple, peach'
pattern = re.compile(r'apple')

result = pattern.search(msg)
if result :
    print('Matched')
else :
    print('Don\'t matched')

import re

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

pattern = re.compile(r'apple')

checkMatch('lemon, apple, peach', pattern)
checkMatch('grapes, cherry', pattern)

import re

def checkMatch(msg, pattern, start, end):
    result = pattern.search(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, 1, 4)

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

$ python3 sample.py 
Matched
apple
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?