0
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

以下のようなパターンでテキスト内に含まれている数字を抜き出すのに、以下の正規表現を使用します

pattern = r'[^+\-\d]*([+-]?\d+([.,]\d+)?).*'

パターン1: 正の整数の場合

text = '123`
result = re.match(pattern, text)
print(result[1])  # => 123

text = '+123`
result = re.match(pattern, text)
print(result[1])  # => +123

パターン2: 負の整数の場合

text = '-123`
result = re.match(pattern, text)
print(result[1])  # => -123

パターン3: 小数を含む場合

text = '123.456`
result = re.match(pattern, text)
print(result[1])  # => 123.456

text = '+123.456`
result = re.match(pattern, text)
print(result[1])  # => +123.456

text = '-123.456`
result = re.match(pattern, text)
print(result[1])  # => -123.456

パターン4: 数字と数字以外の文字が含まれている場合

text = '今日の気温は-10.5度でした`
result = re.match(pattern, text)
print(result[1])  # => -10.5

パターン5: 小数点が,の場合(ヨーロッパで使用されている表記)

text = '今日の気温は-10,5度でした`
result = re.match(pattern, text)
print(result[1])  # => -10,5
0
0
1

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
0
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?