Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.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_Regex - Fatal编程技术网

如何在python中检查字符串格式?

如何在python中检查字符串格式?,python,regex,Python,Regex,我想检查字符串“tDDDDD”,其中D必须是数字,并且不应超过其长度(最小4,最大5) 不允许使用其他字符 目前我的代码是这样检查的 m = re.match('^(t)(\d+)', changectx.branch()) 但它也允许T12345之后的任何内容 我将正则表达式改为 '^(t)(\d\d\d\d)(\d)?$' 这是正确的还是明智的做法?正则表达式可以工作,但也可以使用此正则表达式: r'^t\d{4,5}$' {4,5}是一个量词,表示前面的标记必须出现4到5次 只有当您

我想检查字符串“tDDDDD”,其中D必须是数字,并且不应超过其长度(最小4,最大5)

不允许使用其他字符

目前我的代码是这样检查的

m = re.match('^(t)(\d+)', changectx.branch())
但它也允许T12345之后的任何内容

我将正则表达式改为

'^(t)(\d\d\d\d)(\d)?$'

这是正确的还是明智的做法?

正则表达式可以工作,但也可以使用此正则表达式:

r'^t\d{4,5}$'
{4,5}
是一个量词,表示前面的标记必须出现4到5次

只有当您希望捕获字符串的匹配部分时,这里才需要括号。

这个正则表达式如何:

r'^t\d{4,5}$'
请尝试
re.findall(“^(t\d{4,5})”,“t1234”)
where regex-
^(t\d{4,5})

{m,n}匹配前面RE的m到n个重复

既然你说这里的数字最小值是4,最大值是5,那么m=4&n=5

试试这个

>>> x="t12345anythingafterit."
>>> re.findall("^t\d{4,5}$",x)
[]
>>> x="t12345"
>>> re.findall("^t\d{4,5}$",x) 
['t12345']
>>> x="t1234"
>>> re.findall("^t\d{4,5}$",x)
['t1234']
>>> x="t123"
>>> re.findall("^t\d{4,5}$",x) 
[]