Getting two digits from a string in python with regex

204 Views Asked by At

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()

1

There are 1 best solutions below

0
Austin On BEST ANSWER

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