Extract Numbers and Size Information (KB, MB, etc) from a String in Python
Question: I have a string like this

    
    
    "44MB\n" (it can be anything ranging from 44mb, 44 MB, 44 kb, 44 B)
    

I want to separate `44` and `MB` from the above string. I have written this
code to extract the number

    
    
    import re
    mystring = "44MB\n"
    re.findall(r'\d+', mystring)
    

for extracting the size I want to avoid using `if statements` like

    
    
    if "kb" mystring.lower(): 
        # Do stuffs
    if .......
    

How can I extract the size info using regex


Answer: This script:

    
    
    import re
    
    
    test_string = '44MB\n12b\n6GB\n12pb'
    
    regex = re.compile(r'(\d+)\s*([kmgtp]?b)', re.IGNORECASE)
    
    order = ['b', 'kb', 'mb', 'gb', 'tb', 'pb']
    
    for value, unit in regex.findall(test_string):
        print(int(value) * (1024**order.index(unit.lower())))
    

Will print:

    
    
    46137344
    12
    6442450944
    13510798882111488
    

Which is the sizes it found in bytes.

