pythonregexdigit

Getting two digits from a string in python with regex


I have multiple strings like this 90'4 I want to extract the digits from the string and sum them up to get 94.

I tried compiling the pattern.

pattern="\d'\d"
re.compile(pattern)

I tried the methods findall and match, but did not get what I wanted.

I need to use regex I cannot use .split()


Solution

  • Use \d+ with findall to extract numbers and then find their sum:

    import re
    
    s = "this is 90'4"
    
    numbers = re.findall(r'\d+', s)
    print(sum(map(int, numbers)))
    # 94