正規表現の使用
このステップでは、Python で正規表現を使用して特殊文字を識別する方法を学びます。正規表現は、文字列内のパターンマッチングに強力なツールです。
まず、VS Code エディタを使用して、~/project
ディレクトリに regex_special_characters.py
という名前の Python スクリプトを作成しましょう。
## Content of regex_special_characters.py
import re
def find_special_characters(text):
special_characters = re.findall(r"[^a-zA-Z0-9\s]", text)
return special_characters
text = "Hello! This is a test string with some special characters like @, #, and $."
special_chars = find_special_characters(text)
print("Special characters found:", special_chars)
このコードの動作は以下の通りです。
import re
:この行は re
モジュールをインポートします。このモジュールは正規表現操作を提供します。
def find_special_characters(text):
:これは、文字列を入力として受け取り、その中のすべての特殊文字を見つける関数を定義します。
special_characters = re.findall(r"[^a-zA-Z0-9\s]", text)
:この行は re.findall()
関数を使用して、入力文字列内の英数字(a - z、A - Z、0 - 9)または空白文字(\s
)ではないすべての文字を見つけます。[^...]
は否定文字クラスで、指定されたセットに含まれない任意の文字にマッチします。
return special_characters
:この行は見つかった特殊文字のリストを返します。
- 残りの行は、サンプル文字列を定義し、関数を呼び出してその中の特殊文字を見つけ、結果を出力します。
では、スクリプトを実行しましょう。ターミナルを開き、次のコマンドを実行します。
python regex_special_characters.py
以下の出力が表示されるはずです。
Special characters found: ['!', '@', ',', '#', '$', '.']
この出力は、正規表現を使用して入力文字列内で見つかった特殊文字のリストを示しています。
スクリプトを変更して、句読点文字のみにマッチする別の正規表現を使用しましょう。
VS Code で regex_special_characters.py
を開き、以下のように変更します。
## Modified content of regex_special_characters.py
import re
import string
def find_punctuation_characters(text):
punctuation_chars = re.findall(r"[" + string.punctuation + "]", text)
return punctuation_chars
text = "Hello! This is a test string with some punctuation like ., ?, and !."
punctuation = find_punctuation_characters(text)
print("Punctuation characters found:", punctuation)
この変更後のスクリプトでは、string.punctuation
を使用して、マッチさせる句読点文字のセットを定義しています。
スクリプトを再度実行します。
python regex_special_characters.py
以下の出力が表示されるはずです。
Punctuation characters found: ['!', '.', '?', '!']
この出力は、正規表現と string.punctuation
定数を使用して入力文字列内で見つかった句読点文字のリストを示しています。
正規表現を使用することで、Python の文字列から特殊文字を識別して抽出する柔軟で強力な方法が提供されます。