The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life

--

Chapters
00:00 Question
01:06 Accepted answer (Score 3)
02:04 Answer 2 (Score 0)
02:20 Thank you

--

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

Accepted answer links:
https://www.debuggex.com/

Answer 2 links:
[image]: https://i.stack.imgur.com/b7AIf.png
[image]: https://i.stack.imgur.com/eLEVs.png

--

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