Python: regex search and replace

republicado de http://pythontesting.net/python/regex-search-replace-examples/#in_python

using Python

Search and replace as a filter

I think the most basic form of a search/replace script in python is something like this:
The fileinput module takes care of the stream verses filename input handling.
The re (regex, regular expression) module has sub which handles the search/replace.
The ‘rstrip’ is called on the input just to strip the line of it’s newline, since the next ‘print’ statement is going to add a newline by default.
This handles the case where we don’t want to modify the file.

In place modification of files

A slightly modified script will allow you to modify files, and optionally copy the original file to a backup.
If you leave the ‘backup’ flag out, no backup will be made.
As I’ve shown it with backup=’.bak’, an example.txt.bak file will be created.

with a more complex regular expression

Of course, foo and bar don’t have to be so simple.
For example, the markdown issue I have with converting a table of contents to a series of h2 tags, can be solved with the following script.
Here, I’m looking for things that look like
and replacing it with

Comentários