The Python Oracle

How to match a regular expression with exactly one digit in it using python regex?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 How To Match A Regular Expression With Exactly One Digit In It Using Python Regex?
00:52 Accepted Answer Score 4
01:29 Answer 2 Score 0
01:38 Thank you

--

Full question
https://stackoverflow.com/questions/3816...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 4


If it consists of 1 digit and nothing else:

re.match('^\d$', item)

If it can contain other non-digit characters:

re.match('^\D*\d\D*$', item)

By starting the regex with ^ you just ensured that the first character of item was used in the regex test. By using a $ at the end you will ensure that the last character of item is used in the regex test. By using both ^ and $ in the way shown you will ensure that all the characters of item are used in the test.

Your regex allowed any number of things to happen between the first digit being found and the end of the item string.

This is great resource for testing your regexs:

https://www.debuggex.com/




ANSWER 2

Score 0


I agree with the comments made by user @kaveh. This is what I got:

enter image description here

Results:

enter image description here