题目
编写函数,接收一个任意字符串,返回其中最长的数字字串。要求使用正则表达式。
python题解
- 使用正则表达式re.findall,可以找到所有的数字,
- 其中
+
表示前面的字符匹配1次或多次。 \d
表示匹配的是数字。
- 其中
- 使用sort排序列表,自定义排序规则,使其按字符串长度排序,reverse进行降序排序(默认升序)。
python代码
import re
def str_findMaxLenNum(find_str: str):
# 使用re.finadall, Return a list of all non-overlapping matches in the string.返回字符串中所有不重叠匹配项的列表。
nums = re.findall(r'\d+', find_str)
# 使用list.sort, key的值为一个lambda表达式, 使其排序规则为"按字符串长度排序", reverse=True表示降序排序
nums.sort(key = lambda num: len(num), reverse = True)
return nums[0]
# input一个字符串
find_str = input("输入一个字符串:")
# 调用函数
maxLenNum = str_findMaxLenNum(find_str)
print(maxLenNum)