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で「先読みと後読みを使ったパターンの記述」の動作を確認してみた

Posted at

概要

Pythonで「先読みと後読みを使ったパターンの記述」の動作を確認してみました。
以下のページを参考にしました。

実装

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

sample.py
import re
pattern = re.compile(r'smart(?=phone)')
print(bool(pattern.search('smart')))
print(bool(pattern.search('smartphone')))
print(bool(pattern.search('smartwatch')))
result = pattern.search('smartphone')
print(result.group(0))

import re
pattern = re.compile(r'smart(?!phone)')
print(bool(pattern.search('smart')))
print(bool(pattern.search('smartphone')))
print(bool(pattern.search('smartwatch')))
result = pattern.search('smartwatch')
print(result.group(0))

import re
pattern = re.compile(r'(?<=digital)camera')
print(bool(pattern.search('camera')))
print(bool(pattern.search('digitalcamera')))
print(bool(pattern.search('analogcamera')))
result = pattern.search('digitalcamera')
print(result.group(0))

import re
pattern = re.compile(r'(?<!digital)camera')
print(bool(pattern.search('camera')))
print(bool(pattern.search('digitalcamera')))
print(bool(pattern.search('analogcamera')))
result = pattern.search('analogcamera')
print(result.group(0))

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

$ python3 sample.py 
False
True
False
smart
True
False
True
smart
False
True
False
camera
True
False
True
camera

まとめ

何かの役に立てばと。

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?