Matching Regex in Python
Question: I wanted to match a certain pattern to a few strings with a one regex line (if
possible):

    
    
    blah blah (1023 mega lbs) blah blah 1245 tons
    blah 1023 kilo tons blah blah 1034 metric tons
    blah 1023 feet 345 blah
    $100 is a lot of money
    

I want to match numbers (first occurance in the line, for example) 1023 and
its units (lbs, tons and feet) that may follow it after another word and store
this as another string. However, I have to be careful of $100, because it's
not a unit of measurement that I am concerned with and also any numbers that
may follow the first sequence in that line.

My current approach has many nested `if statements` for example for the first
line I have (not working): `\d*\s(.*)\s\w+` Is there a better way to do this?


Answer: 
    import re
    with open("input") as f:
        for line in f:
            mo=re.match(r'[^\d]*(\d+).*?(tons|feet|lbs)', line)
            if mo: print mo.group(1), mo.group(2)
    

**Output**

    
    
    1023 lbs
    1023 tons
    1023 feet
    

Also, if you have a line like `$100 money is too much for 100 lbs`, you can
use this:

    
    
    import re
    with open("input") as f:
        for line in f:
            mo=re.match(r'.*?(?<![$\d])(\d+).*?(tons|feet|lbs)', line)
            if mo: print mo.group(1), mo.group(2)
    

And to match kilo, mega stuff:

    
    
    import re
    with open("input") as f:
        for line in f:
            mo=re.match(r'.*?(\d+).*?(mega|kilo|metric|) (tons|feet|lbs)', line)
            if mo: print mo.group(1), mo.group(2), mo.group(3)
    

**Output**

    
    
    1023 mega lbs
    1023 kilo tons
    1023  feet
    100  lbs
    

It is possible to store these units and modifiers in lists and join them with
`|` to create a regex on the fly.

An example that matches all possible unit modifiers:

    
    
    import re
    with open("input") as f:
        for line in f:
            mo=re.match(r'[^\d]*(\d+).*?(\S*)\s*(tons|feet|lbs)', line)
            if mo: print "'{}' '{}' '{}'".format(mo.group(1), mo.group(2), 
                           mo.group(3))
    

**Output**

    
    
    '1023' 'mega' 'lbs'
    '1023' 'kilo' 'tons'
    '1023' '' 'feet'
    

