Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I am trying to match a string with exactly one digit in it. e.g. '5', '4', '3', etc. I am using the re library in python to help me use regex.

I have the following three flags that are being set with respective if statements:

import re

if re.match(r'\d{2}:\d{2}:\d{2}', item):
    timeflag = True

if re.match(r'\d{4}', item):
    voltflag = True   

if re.match(r'^\d{1}', item):
    socflag = True

Here is the weird part: when I pass an item with a value say '2754', the socflag still gets set to True, even though it is only supposed to be true when matching a string with only one digit, like '5'.

I am suspecting that my regex syntax is incorrect. So, how do I match a one digit string using python regex?

like image 392
ragzputin Avatar asked Oct 18 '25 03:10

ragzputin


1 Answers

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/

like image 54
Resonance Avatar answered Oct 19 '25 18:10

Resonance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!