Q:

Regex to extract both integer or float values followed by a unit, Python

I want to build a regex which captures all patterns inside a string where an integer or a floating point number is present before an unit of measurement(ml,mg,kg etc). My current regex only considers integers and breaks when there's a space. I want to handle these in my code.
p = re.compile('[0-9](?:mg|kg|ml|q.s.|ui|M|g|µg)')
x = '0.9mg is the approximate dosage'
z = p.findall(x)
print(z)

which doesn't work for decimals and also breaks when there's a space.
Expected patterns to be captured are:
Examples: 0.9 mg, 9 mg, 9mg, 0.9mg

Any help regarding this
Using the regex in the code:
mg = []
newregex = r"[0-9\.\s]+(?:mg|kg|ml|q.s.|ui|M|g|µg)" 
for s in zz:
    for e in extracteddata:
        v = re.search(newregex,extracteddata,flags=re.IGNORECASE|re.MULTILINE)
        if v:
            mg.append(v.group(0))

A:

(?<!\d|\.)\d+(?:\.\d+)?\s*?(?:mg|kg|ml|q\.s\.|ui|M|g|µg)(?!\w)
This regex will select properly formatted numbers with properly formatted units after them, and will reject badly formed numbers or non-existent units.

(?<!\d|\.) - make sure there's no digits or decimal points before this number.
\d+ - get one or more digits.
(?:\.\d+)? - optionally get a decimal point, followed by one or more digits. 
\s*? - get zero to unlimited whitespace characters, as few as possible.
(?:mg|kg|ml|q\.s\.|ui|M|g|µg) - capture one of the listed units.
(?!\w) - make sure there's no extra data following the captured unit. 

Regex demo

import re

p = re.compile('(?<!\d|\.)\d+(?:\.\d+)?\s*?(?:mg|kg|ml|q\.s\.|ui|M|g|µg)(?!\w)')
x = 'Examples: 0.9 mg, 9 mg, 9mg, 0.9mg'

print(p.findall(x))

['0.9 mg', '9 mg', '9mg', '0.9mg']

Python demo

A:

You can try with this:
([.\d]+)\s*(?:mg|kg|ml|q.s.|ui|M|g|µg)

Try it online.

