tags:

views:

853

answers:

2

Assume infile is a variable holding the name of an input file, and similarly outfile for output file. If infile ends in .js, I'd like to replace with .min.js and that's easy enough (I think).

outfile = re.sub(r'\b.js$', '.min.js', infile)

But my question is if infile ends in .min.js, then I do not want the substitution to take place. (Otherwise, I'll end up with .min.min.js) How can I accomplish this by using regular expression?

PS: This is not homework. If you're curious what this is for: this is for a small python script to do mass compress of JavaScript files in a directory.

+9  A: 

You want to do a negative lookbehind assertion. For instance,

outfile = re.sub(r"(?<!\.min)\.js$", ".min.js", infile)

You can find more about this here: http://docs.python.org/library/re.html#regular-expression-syntax

Evan Fosmark
Just what I was going to say.
cletus
+3  A: 

For tasks this simple, there's no need for regexps. String methods can be more readable, eg.:

if filename.endswith('.js') and not filename.endswith('.min.js'):
    filename= filename[:-3]+'.min.js'
bobince
yep, I knew that, but the question provides a good chance for me to learn more about regex.
Khnle