Reputation: 10857
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
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
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