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'Ha*n')
print(bool(pattern.search('Hn')))
print(bool(pattern.search('Han')))
print(bool(pattern.search('Haaaaan')))
print(bool(pattern.search('HaaUaan')))

import re
pattern = re.compile(r'Ha+n')
print(bool(pattern.search('Hn')))
print(bool(pattern.search('Han')))
print(bool(pattern.search('Haaaaan')))
print(bool(pattern.search('HaaUaan')))

import re
pattern = re.compile(r'Ha?n')
print(bool(pattern.search('Hn')))
print(bool(pattern.search('Han')))
print(bool(pattern.search('Haaaaan')))
print(bool(pattern.search('Ham')))

import re
pattern = re.compile(r'Ha{3}n')
print(bool(pattern.search('Haaan')))
print(bool(pattern.search('Han')))
print(bool(pattern.search('Haaaaan')))
print(bool(pattern.search('HaaaO')))

import re
pattern = re.compile(r'Ha{2,4}n')
print(bool(pattern.search('Haan')))
print(bool(pattern.search('Haaaan')))
print(bool(pattern.search('Haaaaan')))
print(bool(pattern.search('HaaaO')))

import re
pattern = re.compile(r'<em>.*</em>')
msg = '<p>今日は<em>快晴の</em>一日です</p>';
result = pattern.search(msg)
print(result.group(0))
pattern = re.compile(r'[0-9]{3}-[0-9]{4}')
msg = '郵便番号は 123-4567 です';
result = pattern.search(msg)
print(result.group(0))

import re
pattern = re.compile(r'(\d{1,3}\.){3}\d{1,3}')
msg = 'IPアドレスは 192.168.0.18 です';
result = pattern.search(msg)
print(result.group(0))

import re
pattern = re.compile(r'b.*a')
msg = 'breakfast is sandwich';
result = pattern.search(msg)
print(result.group(0))

import re
pattern = re.compile(r'b.*?a')
msg = 'breakfast is sandwich';
result = pattern.search(msg)
print(result.group(0))

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

$ python3 sample.py 
True
True
True
False
False
True
True
False
True
True
False
False
True
False
False
False
True
True
False
False
<em>快晴の</em>
123-4567
192.168.0.18
breakfast is sa
brea

まとめ

何かの役に立てばと。

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?