Regular expression: replace the suffix of a line ending in .js but not "min.js"

Suppose infile is a variable containing the name of the input file and a similar outfile for the output file. If the infile ends with .js , I would like to replace .min.js and it is quite simple (I think).

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

But my question is: if the infile ends in .min.js , then I do not want the replacement to be done. (Otherwise, I ended up with .min.min.js ). How can I do this using regex?

PS: This is not homework. If you are wondering what it is for: this is for a small python script for massively compressing JavaScript files in a directory.

+3
source share
2 answers

You want to make a negative lookbehind statement. 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

+9
source

For tasks, it's simple; no regular expressions are needed. String methods can be more readable, for example:

if filename.endswith('.js') and not filename.endswith('.min.js'):
    filename= filename[:-3]+'.min.js'
+3
source

All Articles