Python 正則表示式從字串中提取最大數字
使用正則表示式從字串中提取最大數字的最簡單方法是
- 使用 RegEx 模組從字串中提取所有數字
- 從這些數字中找出最大值
例如,對於輸入字串
這個城市有 121005 人,鄰近城市有 1587469 人,遠處的城市有 18775994 人。
我們應該得到以下輸出
18775994
我們可以使用“\d+”正則表示式找到字串中的所有數字,因為 “\d”表示數字,“加號”查詢連續數字的最長字串。我們可以使用 re 包按照以下方法來實現它
import re
# Extract all numeric values from the string.
occ = re.findall("\d+", "There are 121005 people in this city, 1587469 in the neighbouring city and 18775994 in a far off city.")
# Convert the numeric values from string to int.
num_list = map(int, occ)
# Find and print the max
print(max(num_list))這將提供以下輸出
18775994
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP