Retrieve Exactly 1 Digit Using Regular Expression In Python
I want to print only ages that are less than 10. In this string, only the value 1 should be printed. Somehow, that is not happening. I used the following codes (using regular exp
Solution 1:
You are trying to match "any 1 number", but you want to match "any 1 number, not followed or preceded by another number".
One way to do that is to use lookarounds
re.findall(r'(?<![0-9])[0-9](?![0-9])', s5)
Possible lookarounds:
(?<!R)S // negativelookbehind: match S thatisnotprecededby R
(?<=R)S // positivelookbehind: match S thatisprecededby R
(?!R)S // negativelookahead: match S thatisnotfollowedby R
(?=R)S // positivelookahead: match S thatisfollowedby R
Maybe a simpler solution is to use a capturing group ()
. if regex in findall
has one capturing group, it will return list of matches withing the group instead of whole matches:
re.findall(r'[^0-9]([0-9])[^0-9]', s5)
Also note that you can replace any 0-9
with \d
- character group of numbers
Solution 2:
Try this :
k = re.findall('(?<!\S)\d(?!\S)', s5)
print(k)
This also works :
re.findall('(?<!\S)\d(?![^\s.,?!])', s5)
Solution 3:
import re
s = "The baby is 1 year old, Sri is 45 years old, Ann is 50 years old; their father, Sumo is 78 years old and their grandfather, Kris, is 100 years old"
m = re.findall('\d+',s)
for i in m:
ifint(i)<10:
print(i)
Post a Comment for "Retrieve Exactly 1 Digit Using Regular Expression In Python"