Search code examples
regexreplacepython-idle

In Python IDLE How to replace one character in regex search in replace dialog?


Let's say I have bunch of lines like this:

file.write('string')

and want to rewrite them fast into

text += 'string'

I can replace the file.write( part without using regex because I want to replace all such occurrences. But for the ending part, how can I do it using the Python IDLE replace dialog window? I can find it using (file.write).*(\)$) but now I want to replace just the last character. Is there some trick to be able to do that instead of just replacing the whole thing?

enter image description here


Solution

  • ( ) has special meaning in regex and you should use it in different way.

    You should use ( ) with .* to catch 'string' and later put it as \1 in new code.

    Because ( ) has special meaning so I use \( and \) to skip original ( ) in code.

    Find: file.write\((.*)\)$

    Replace: text += \1

    enter image description here