Kannaiyan
Kannaiyan

Reputation: 13025

How to check for a string format in python?

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

Answers (4)

Abhijit
Abhijit

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

Srikar Appalaraju
Srikar Appalaraju

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

Ya Zhuang
Ya Zhuang

Reputation: 4660

how about this regex:

r'^t\d{4,5}$'

Upvotes: 2

Mark Byers
Mark Byers

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

Related Questions