
如何判断一串数字符合指定格式?
您需要判断一组数字是否符合以下格式:
- 最少包含 6 位,最多包含 7 位
- 用空格分隔
- 只能包含数字或 '*'
解决方案:
可以使用 Python 中的正则表达式来轻松判断:
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示例:
以下代码示例展示了如何使用该函数:
input_a = "1 2 3 4 5 6" input_b = "* 2 3 4 5 6" input_c = "1 2 3 4 5 6 7" print(check_format(input_a)) # True print(check_format(input_b)) # True print(check_format(input_c)) # False










