简体   繁体   中英

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 expression python)

import re

# This is my string

s5 = "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"


# print all the single digits from the string
re.findall('[0-9]{1}', s5)
# Out[153]: ['1', '4', '5', '5', '0', '7', '8', '1', '0', '0']

re.findall('\d{1,1}', s5)
# Out[154]: ['1', '4', '5', '5', '0', '7', '8', '1', '0', '0']

re.findall('\d{1}', s5)
# Out[155]: ['1', '4', '5', '5', '0', '7', '8', '1', '0', '0']

The output should be 1 and not all the digits as displayed above.

What am i doing wrong ?

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   // negative lookbehind: match S that is not preceded by R
(?<=R)S   // positive lookbehind: match S that is preceded by R
(?!R)S   // negative lookahead: match S that is not followed by R
(?=R)S   // positive lookahead: match S that is followed by 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

Try this :

k = re.findall('(?<!\S)\d(?!\S)', s5)
print(k)

This also works :

re.findall('(?<!\S)\d(?![^\s.,?!])', s5)
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:
    if int(i)<10:
        print(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM