Search code examples
pythonregexlinuxstringsubstring

Python extract sub string in between two pattern excluding floating number


I am using python 2. I need to replace two sections in a string. For example something like below

str1 = "product,price=(decimals=4, value=7.505),quantity"
str2 = "product,(subporduct,(price=(decimals=4, value=7.05)),quantity"
str3 = "product,(subporduct,item=2, price=(decimals=4, value=7.05)),quantity"

I need the out put to be like this i.e. with price equals to the floating number

  1. product,price=7.505,quantity
  2. product,(subporduct,(price=7.05),quantity
  3. product,(subporduct,item=2, price=7.05),quantity

I tried this but it leaves the last bracket, otherwise it is good enough for me.

print(re.sub("(?<=price=).+?(?<=value=)", "", str1))

I need the solution in python 2


Solution

  • You can use

    re.sub(r'(price=)\([^()]*?value=([\d.]+)\)', r'\1\2', str1)
    

    See the regex demo. Details:

    • (price=) - Group 1 (\1): price= substring
    • \( - a ( char
    • [^()]*? - zero or more chars other than ( and ) as few as possible
    • value= - a literal substring
    • ([\d.]+) - Group 2 (\2): one or more digit or . chars
    • \) - a ) char.

    The replacement is the concatenation of Group 1 and 2 values.