Search code examples
pythonregexstringtext

How to extract human height (US) from string


If I have a string that contains a human height in the US form (feet, inches)
e.g. I've been 5'10" since I was 18
how can I use regex to extract the 5'10" as a tuple?
e.g. (5, 10)

So far I tried:

s = "I've been 5'10\" since I was 18"
re.findall(r'\d\'\d+\"', s)

Hoping to grab the first digit, which should be a single digit \d and then the next two digits with \d+, but this doesn't work very cleanly, returning ['5\'10"'] and requiring more splitting etc. Ideally there is a way to do this all with regex.


Solution

  • import re
    a='''I've been 5'10" since I was 18''' #triple quotes to account for " after 10
    p=re.compile(r"[0-9]+'[0-9]{2}\"")
    print(re.findall(p,a)[0])
    

    And Voila !