How to get only numbers in parentheses in Python with regular expression

0
Texto = "54 oz (163 g)"

I want the result to be only 163

    
asked by anonymous 09.04.2018 / 05:41

2 answers

3

You can do this:

\((\d+) g\)

The first and last counterbar is to escape the parentheses, (\d+) will capture only the digits within the parentheses. The complete code:

import re
Texto = "54 oz (163 g)"
Resultado = re.search('\((\d+) g\)', Texto)
print(Resultado[1])
  

You can see it working at repl.it

    
09.04.2018 / 06:07
2

A complement to the response from @wmsouza.

If the unit of measure is scaled (mg, g, kg, and so on), the regular expression can be changed '((\ d +) \ w +)' as shown in the excerpt below:

Resultado = re.search('\((\d+) \w+\)', Texto)
print(Resultado.group(1))
    
09.04.2018 / 16:01