3

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?

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

how about this regex:

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

Comments

1

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.

Comments

1

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) 
[]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.