1

I searched for an answer to my question on this site. There are answered questions like:

but I'm not able to transform the information to my problem, so:

I need to replace a specific value in a text file. The file structure looks like this:

black
{
    part cone;
    value 20;
}
yellow
{
    part wing;
    value 30;
}

In a GUI the user defines the color and the new value. For example: black = 30. If the user starts the script, the input values are a="black" and b=30.

My piece of code:

dpd=open("colors","r+")
ft=dpd.read()
ft_new=re.sub(???,???,ft)
dpd.seek(0)
dpd.write(ft_new)
dpd.truncate()
dpd.close()

I tried something like this:

re.sub(str(a)+'\n.*\n.*\n.*value [0-9][0-9]?',str(a)+'\n.*\n.*\n.*?value '+str(b),ft)

but this does not work. I understand how to substitute a single string but I don't get how to substitute a specific value in a specific place in the file.

Nander Speerstra
  • 1,496
  • 6
  • 24
  • 29
finkae
  • 13
  • 3
  • You need a capturing group and a replacement backreference. Something like `re.sub(r'(?m)^({}\n{{\n.*\n\s*value\s+)\d+'.format(a), r'\g<1>{}'.format(b), ft)` - see [this regex demo](https://regex101.com/r/sgh2rV/1) – Wiktor Stribiżew Nov 07 '17 at 09:50
  • thank you very much. it works. now i will try to understand it with turtorials etc. thanks again. i would like to upvote your answer but i don't get it how to do it. – finkae Nov 07 '17 at 10:16

1 Answers1

0

You may use

ft_new = re.sub(r'(?m)^({}\n{{\n.*\n\s*value\s+)\d+'.format(a), r'\g<1>{}'.format(b), ft)

The pattern will look like

(?m)^(black\n{\n.*\n\s*value\s+)\d+

See the regex demo

Details

  • (?m)^ - start of the line
  • (black\n{\n.*\n\s*value\s+) - Group 1:
    • black - black
    • \n{\n - newline, {, newline
    • .* - the whole line
    • \n\s* - newline and then 0+ whitespaces
    • value - a value substring
    • \s+ - 1+ whitespaces
  • \d+ - 1 or more digits.

The replacement, \g<1>30, consists of two parts:

  • \g<1> - an unambiguous backreference to Group 1
  • 30 - 30 value

Please go through the 7.2.1. Regular Expression Syntax.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563