Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 确定输入是否与指定格式匹配_Python_Input_Format - Fatal编程技术网

Python 确定输入是否与指定格式匹配

Python 确定输入是否与指定格式匹配,python,input,format,Python,Input,Format,Python3中是否有一个选项来确定输入是否匹配指定的格式?例如:格式为d-dddd-dddd-d,其中d代表数字(0-9): 试试这个: string = "9-9715-0210-0" split = string.split("-") if len(split[0]) == 1 and len(split[1]) == 4 and len(split[2]) == 4 and len(split[3]) == 1: print(True) else: print(False

Python3中是否有一个选项来确定输入是否匹配指定的格式?例如:格式为
d-dddd-dddd-d
,其中
d
代表数字(0-9):

试试这个:

string = "9-9715-0210-0"
split = string.split("-")
if len(split[0]) == 1 and len(split[1]) == 4 and len(split[2]) == 4 and len(split[3]) == 1:
    print(True)
else:
    print(False)

您还可以将字符串更改为
输入
,以便输入输入或从此代码创建函数并多次运行。

使用正则表达式的工作方式如下:

import re

regex = r'\d-\d{4}-\d{4}-\d'

preg = re.compile(regex)

s1 = '9-9715-0210-0'
s2 = '997-150-210-0'

m1 = preg.match(s1)
m2 = preg.match(s2)

if m1:
    print('String s1 is valid')
else:
    print('String s1 is invalid')

if m2:
    print('String s2 is valid')
else:
    print('String s2 is invalid')   
您可以在上尝试代码


你在下面的评论中提出的正则表达式只是我的长版本。因此,这也应该起作用。

您可以使用“正则表达式”,请参阅。一个起点是:像这样的东西是不是可以“string=input()pattern=\d-\d\d\d-\d\d\d-\d result=re.match(pattern,string)”@Aleandro您为什么不试试看呢?这非常脆弱;如果少于3个
-
组,它将抛出
索引器,忽略任何后续的
-
分隔组,并且不关心每个组中的字符是否为数字。请注意
{1}
是冗余的,并且是正则表达式。
import re

regex = r'\d-\d{4}-\d{4}-\d'

preg = re.compile(regex)

s1 = '9-9715-0210-0'
s2 = '997-150-210-0'

m1 = preg.match(s1)
m2 = preg.match(s2)

if m1:
    print('String s1 is valid')
else:
    print('String s1 is invalid')

if m2:
    print('String s2 is valid')
else:
    print('String s2 is invalid')