How to use Matlab/Octave regexprep (regular expression replace) to add suffix to file name before extension

Viewed 354

Say I have this Matlab or Octave char variable:

>> filename = 'my.file.ext'

I want a regexprep command that adds a suffix, say '_old', to the file name before the extension, transforming it into 'my.file_old.ext'.

The following replaces all dots with '_old.':

>> regexprep(filename, '\.', '_old.')
ans =
    'my_old.file_old.ext'

What is a regexprep command that prepends '_old' only to the last dot? (Ideally, if there is no dot (no extension), append '_old' at the very end.)

Thank you in advance!

2 Answers

If doing it without regular expressions is an option, you can use fileparts as follows:

filename  = 'my.file.ext';
suffix = '_old';
[p, n, e] = fileparts(filename); % path, file, extension; each possibly empty
result = [p, n, suffix, e];

Example in Octave.

You may use

regexprep(filename, '^(?:(.*)(\.)|(.*))', '$3$1_old$2')

See the regex demo

Details

  • ^ - start of string
  • (?:(.*)(\.)|(.*)) - a non-capturing group matching either of the two alternatives:
    • (.*)(\.) - Group 1 ($1 backreference refers to the value of the group): any zero or more chars as many as possible and then Group 2 ($2): a dot
    • | - or
    • (.*) - Group 3 ($3): any zero or more chars as many as possible

If an alternative is not matched, the backreference to the capturing group is an empty string. Thus, if (.*)(\.) matches, the replacement is Group 1 + _old + Group 2 value. Else, it is Group 3 + _old (just appending at the end).

Related