Python 正規表現を使用して文字列からすべての数字を抽出
Python では、次を使用できますreモジュールを使用して正規表現を処理します。文字列からすべての数字を抽出するには、次を使用できますre.findall()関数。これは正規表現に一致するすべての部分文字列を返すことができます。
実例
import re
# サンプル文字列
text = "The price is 45 dollars and 30 cents."
# 正規表現を使用してすべての数字を抽出
numbers = re.findall(r'd+', text)
print(numbers)
# サンプル文字列
text = "The price is 45 dollars and 30 cents."
# 正規表現を使用してすべての数字を抽出
numbers = re.findall(r'd+', text)
print(numbers)
コード解析:
import re:Python の正規表現モジュールをインポートします。text = "The price is 45 dollars and 30 cents.":数字を含む文字列を定義します。re.findall(r'd+', text):使用re.findall()関数で文字列内の正規表現に一致するすべてのd+部分文字列を検索します。d+1つ以上の連続した数字に一致します。print(numbers):抽出されたすべての数字を出力します。
出力結果:
['45', '30']その他の拡張
Python3 実例