1

I'm writing a script which finds in a file a few lines of text. I wonder how to replace exactly that text with other given (new string might be shorter or longer). I'm using re.compile() to create a multiple line pattern then looking for any match in a file I do like this:

for match in pattern.finditer(text_in_file)
    #if it would be possible I wish to change 
    #text in a file here by (probably) replacing match.group(0)

Is it possible to accomplish in this way (if yes, then how to do it in the easiest way?) or my approach is wrong or hard to do it right (if yes, then how to do it right?)

1
  • 1
    Use re.sub not re.finditer. Commented Jan 22, 2014 at 16:43

2 Answers 2

2

The simple solution:

  1. Read the whole text into a variable as a string.
  2. Use a multi-line regexp to match what you want to replace
  3. Use output = pattern.sub('replacement', fileContent)

The complex solution:

  1. Read the file line by line
  2. Print any line which doesn't match the start of the pattern
  3. If you find a match for the start, stop printing until you see the end pattern.
  4. If you saw the end pattern, print the replacement
Sign up to request clarification or add additional context in comments.

Comments

1

Use pattern.sub('replacement text', text_in_file) to replace matches.

You can use back references in the replacement pattern as needed. It doesn't matter if the string is shorter or longer; the method returns a new string value with the replacements made. If the text came from a file, you'll need to write back the text to that file to replace the contents.

You could use the fileinput module if you need to make the replacement in-place; the module takes care of moving the original file aside and write a new file in it's place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.