Home > Back-end >  Extract number outside the parentheses in python
Extract number outside the parentheses in python

Time:08-21

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!

CodePudding user response:

Does this answer your question?

import re

text = '4.0718393*nt(placement5,placement6) 4.021677*nt(placement4)'
matches = re.findall(r"\d \.\d ", text)

CodePudding user response:

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']
  • Related