
一组数格式判断
给定一组数字,要求最少有 6 位,最多有 7 位,每个数字之间用空格隔开,且只能输入数字或星号。例如:
- 1 2 3 4 5 6
- * 2 * 4 5 6
- 1 2 3 4 * 6
如何判断给定的数字串是否满足以上格式要求?
判断方法
可以使用正则表达式来判断:
import re
def check_format(input_string):
# 正则表达式匹配 6 或 7 个由空格分隔的数字或星号
pattern = r'^(\d|\*)+(\s(\d|\*)+){5,6}$'
match = re.fullmatch(pattern, input_string)
return match is not None- ^表示行首。
- (\d|\*)+匹配一个或多个数字或星号。
- (\s(\d|\*)+){5,6}匹配 5 到 6 个由空格分隔的数字或星号的组。
以下是使用此函数判断一些字符串的例子:
>>> check_format('1 2 3 4 5 6')
True
>>> check_format('* 2 * 4 5 6')
True
>>> check_format('1 2 3 4 * 6')
True
>>> check_format('1 2 3 4 5 6 7')
False
>>> check_format('1 2 3 4 *')
False










