Extract number outside the parentheses in python

Question:

I have the problem with this string

'4.0718393*nt(placement5,placement6)+4.021677*nt(placement4)'

and want have this result

[4.0718393, 4.021677]

Simply said, I want to extract the numbers outside the parentheses in python. I found this regex pattern which will extract every number in a string and is not helping me get further.

re.findall("[-+]?d+[.]?d*[eE]?[-+]?d*", string) 

Much appreciated!

Asked By: Zyy

||

Answers:

Does this answer your question?

import re

text = '4.0718393*nt(placement5,placement6)+4.021677*nt(placement4)'
matches = re.findall(r"d+.d+", text)
Answered By: Jobo Fernandez

Number can be at the start, at the end of the string. Or in two cases in the middle of the string. One case surrounded by brackets, the other not surrounded by brackets. To avoid in this case numbers in brackets in this particular case one may use this regex in re.findall.

[)][^(]*(d+.d+)[^)]*[(]

s = '4.0718393*nt(placement5,2739.14*placement6,44.555)+4.021677*nt(placement4.0),777.311'
    
    list(filter(None,(chain(*re.findall(r',(d+.d+)$|^(d+.d+)|[)][^(]*(d+.d+)[^)]*[(]',s)))))
    
    ['4.0718393', '4.021677', '777.311']
Answered By: LetzerWille

If you only want to extract the decimal number use this regex expression
d+(.d+)+

import re

text = '4.0718393*nt(placement5,placement6)+4.021677*nt(placement4)'
matches = re.findall(r"d+(.d+)+", text)
Answered By: sudayn
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.