Python Regex从字符串中提取最大数值
使用正则表达式从字符串中提取最大数值的最简单方法是-
使用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
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西