Search code examples
pythonfilepython-re

Change int between 2 strings


I need to replace int between 2 strings or something like that. ex:

["revolter"] = {
    ["name"] = "Revolter",
    aaaa = 195000, #This value (195000) needs to be tripled
    ["category"] = "sports",
    ["shop"] = "pdm",
},
["blade"] = {
    ["name"] = "Blade",
    aaaa = 19000,#This value (19000) needs to be tripled
    ["category"] = "muscle",
    ["shop"] = "pdm",
},

My code atm:

import re

f = open("fail.txt","r")
faili_sisu = f.read()
f.close()
new_value = #
faili_sisu = re.sub(r"(.*?aaaa = ).*?(,.*)", r"\1replaceble_int\2", faili_sisu)
faili_sisu = faili_sisu.replace("replaceble_int", str(new_value))

f = open("fail.txt", "w")
f.write(faili_sisu)
f.close()

I would like to know how can I get this int/str between "aaaa = " and "," to variable


Solution

  • The replacement in re.sub() can be a function. It can convert the matched string to an integer and multiply it.

    faili_sisu = re.sub(r'(?<=aaaa = )\d+', lambda m: str(3 * int(m.group(0))), faili_sisu)
    

    DEMO