Problem with regexp and text injection

chris.monsanto at gmail.com chris.monsanto at gmail.com
Sun Oct 21 19:49:13 EDT 2007


On Oct 21, 6:22 pm, Panagiotis Atmatzidis <p.atmatzi... at gmail.com>
wrote:
> Hello,
>
> I want to create a script in python that search for .html files in the
> predefined directory and subdirectories. Then it checks if a specific
> snippet of code exists in the .html file, if not it injects/adds the
> code right below the string <body> otherwise bypasses the file.
>
> I wrote the first part, I managed to write search function and I'm
> trying to find my way out of regular expressions reading the manuals.
> However I don't know what kind of function and module to use in order
> to write this function, re.search(), re.string() or re.match() or
> maybe re.compile() ?
>
> I have not much programming experience. Programming is not my cup of
> tea.
>
> Can someone help by pointing me to a sample code with comments if
> possible.
>
> Regards,
>
> atma

import glob
glob.glob("*.html") # returns a list of all filenames you are looking
for

---------

import re
m = re.search(regular_expression_testing_for_string_of_code,
string_with_contents_of_page) # checks if your snippet is there
if m is None:
    new_contents = re.sub(r"(?xis) <body .*?>", lambda m: m.group() +
your_snippet_of_code, string_with_contents_of_page) # Add the snippet
to the body. I use a function as the replacement in case your snippet
has backreferences in it for some reason. If it doesn't, feel free to
use r"\0" + snippet_of_code.





More information about the Python-list mailing list