How to pick only numbers between parentheses in Python with regular expression

Asked

Viewed 829 times

0

Texto = "54 oz (163 g)"

I want the result to be only 163

2 answers

3

You can do it like this:

\((\d+) g\)

The first and last counter-bar 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 in repl it.

  • If you don’t want to work with groups, an adaptation of this expression would be this: (?!\()\d+(?=\s*[a-zA-Z]\)), in which the demo can be seen in this link

  • @danieltakeshi it would be interesting if you put her as an answer!

2

A complement to @wmsouza’s reply.

If the unit of measurement is scalar (mg, g, kg, and so on), the regular expression may be changed '((\d+) w+)' as presented in the section below:

Resultado = re.search('\((\d+) \w+\)', Texto)
print(Resultado.group(1))
  • Just an addendum, I also get confused with the \w, but w is equivalent to: [a-zA-Z0-9_]. Then it would capture numbers as well. But this expression would work in the example given by OP.

  • @danieltakeshi would work perfectly. However, in my personal analysis, for reading and maintaining code, the simple is better. ;D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.