1
0

Pythonで「正規表現にマッチした文字列を新しい文字列に置換する(Pattern.sub, Pattern.subn)」の動作を確認してみた

Posted at

概要

Pythonで「正規表現にマッチした文字列を新しい文字列に置換する(Pattern.sub, Pattern.subn)」の動作を確認してみました。
以下のページを参考にしました。

実装

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

sample.py
import re

msg = 'Border is Red, Box is red, Line is RED'
pattern = re.compile(r'Red|RED')

result = pattern.sub('red', msg)
print(result)

import re

msg = 'Border is Red, Box is red, Line is RED'
pattern = re.compile(r'Red|RED')

result = pattern.subn('red', msg)
print(result)

import re

msg = 'Red Blue Yellow Pink Green White'
pattern = re.compile(r'\b[a-zA-Z]+?\b')

result = pattern.sub('***', msg)
print(result)

import re

msg = 'Red Blue Yellow Pink Green White'
pattern = re.compile(r'\b[a-zA-Z]+?\b')

result = pattern.sub('***', msg, 2)
print(result)

import re

msg = '次の会議は 2020-12-03 です'
pattern = re.compile(r'(\d{4})-(\d{2})-(\d{2})')

result = pattern.sub(r'\1年\2月\3日', msg)
print(result)

import re

msg = 'Product is AE-42'
pattern = re.compile(r'(?P<cate>[A-Z]{2})-(?P<code>[0-9]{2})')

result = pattern.sub(r'Category=\g<cate>/Code=\g<code>', msg)
print(result)

import re

msg = 'Border is Red, Box is Green, Line is BLUE'
pattern = re.compile(r'\b[a-zA-Z]+?\b')

def replaceStr(m):
    s = m.group(0)
    return s.lower()

result = pattern.sub(replaceStr, msg)
print(result)

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

$ python3 sample.py 
Border is red, Box is red, Line is red
('Border is red, Box is red, Line is red', 2)
*** *** *** *** *** ***
*** *** Yellow Pink Green White
次の会議は 2020年12月03日 です
Product is Category=AE/Code=42
border is red, box is green, line is blue

まとめ

何かの役に立てばと。

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