使用 正則表示式 從字串中提取最大數值的 Python 方法


使用正則表示式從字串中提取最大數值的最簡單方法是 -

  • 使用正則表示式模組從字串中提取所有數字
  • 從這些數字中找到最大值

例如,對於輸入字串 -

這座城市有 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

更新於: 20-06-2020

385 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.