Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

Replace the suffix of a string ending in '.js' but not 'min.js' with a regular expression

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.

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 a regular expression?

Upvotes: 3

Views: 1933

Answers (2)

bobince
bobince

Reputation: 536469

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'

Upvotes: 3

Evan Fosmark
Evan Fosmark

Reputation: 101711

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

Upvotes: 9

Related Questions