Reputation: 13025
I would like to check for string "tDDDDD" where D has to be digits and should not be more than the length (minimum 4, maximum 5) of it.
No other characters allowed.
Currently my code checks like this,
m = re.match('^(t)(\d+)', changectx.branch())
But is also allows t12345anythingafterit.
I changed the regular expression to
'^(t)(\d\d\d\d)(\d)?$'
Is this correct or any smart way of doing it?
Upvotes: 3
Views: 482
Reputation: 63737
Try this
>>> 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)
[]
Upvotes: 1
Reputation: 73608
Try re.findall('^(t\d{4,5})', "t1234")
where regex - ^(t\d{4,5})
{m,n} Matches from m to n repetitions of the preceding RE.
Since you say the digits are a min of 4 and a max of 5 here, m=4 & n=5.
Upvotes: 1
Reputation: 838236
Your regular expression will work, but you could also use this regular expression:
r'^t\d{4,5}$'
The {4,5}
is a quantifier that means the previous token must occur between 4 and 5 times.
The parentheses are only necessary here if you wish to capture the matching parts of the string.
Upvotes: 7