I have had written text file in which I have statements like these :
WriteByte(0x6000, 0x28); // Register Value ...
WriteByte(0x6002, 0x02); //
WriteByte(0x6004, 0x08); //
I have to replace 0x28 with a user given value as an input
This means I have replace 0x28 with usr_value which may be 0x35 or 0x38 etc..
Also I also cant count on there being only 0x28 it coould be any other value whose contents are to be replaced by user given content.
Also since the text file is hand written it could have extra spaces or not
WriteByte(0x6000,0x28); // Register Value ...
or
WriteByte( 0x6000 , 0x28); // Register Value ...
I tried using string.replace but it may not work for all combinations.
What’s the best way of doing this apart from using Regular expressions ?
From the discussion below, if you want to find all the second arguments to WriteBytes and prompt for replacing, you can do something like this:
parse the file to find all the 2nd arguments to WriteBytes, using a regular expression, and store them in a set (which will handle duplicates for you)
for all the values you’ve seen, prompt the user for the replacement value, and store that in a dictionary
read the file again, and perform the replacements, storing the modified lines in a list, together with the unmodified lines
write the data back to disk.
Sample code:
You can avoid reading the file twice at the cost of a slightly more complicated code (left as an exercise to the reader)