jeff
jeff

Reputation: 13653

How to ensure string ends with a certain substring in MATLAB

I'm processing a set of strings in a for loop, but I want to make sure the strings end with '.jpg', so in some cases the string is in the format str = 'filename.jpg.mat', in this case, I need to detect the last 4 characters as redundant, hence I need to convert str to 'filename.jpg'

In other words, I'm looking for a function in this form:

function new_str = fix_end(str, wanted_ending)

So when I call

fix_end('filename.jpg.mat', '.jpg'),

it should return 'filename.jpg'.

Is there a MATLAB (fast) way to do this?

Thanks for any help!

Edit

  1. It is safe to assume that wanted_ending will only occur once in str.
  2. The redundant part does not have to be '.mat', it can be anything. So I just want to delete whatever there is after '.jpg'.

Upvotes: 0

Views: 748

Answers (3)

Suever
Suever

Reputation: 65430

You can easily do this with regular expression replacement (regexprep). This looks for names that have something after .jpg and removes it.

names = {'file1.jpg.mat', 'file2.jpg.mat2', 'file3.jpg.mat3', 'file4.jpg'}

newnames = regexprep(names, '(?<=\.jpg).*', '');
%    'file1.jpg'    'file2.jpg'    'file3.jpg'   'file4.jpg'

Or more generally, the following which accepts the ending that you want to keep and remove anything that comes afterwards.

function new = fix_end(str, ending)
    new = regexprep(str, ['(?<=', regexptranslate('escape', ending), ').*'], '');
end

fix_end('file1.jpg.mat', '.jpg')
%   file1.jpg

As a sidenote, if all you really need is for all the strings to end in .jpg, why not just append .jpg to all strings regardless of what their previous extension was?

new_str = [str, '.jpg'];

As suggested by @Mohsen, you can also use the following

newnames = regexp(names, '^.*\.jpg', 'match', 'once');

Or as a function:

function new = fix_end(str, ending)
    new = regexp(str, ['^.*', regexptranslate('escape', ending)], 'match', 'once');
end

Upvotes: 2

Dan
Dan

Reputation: 45752

I think this will work for your case

function new_str = fix_end(str, wanted_ending)
    new_str = [str(1:strfind(str,wanted_ending)-1), wanted_ending]
end

It might be faster to use strrep if it's always .mat that you want to get rid of so either:

strrep(str,'.jpg.mat','.jpg')

or

strrep(str,'.mat','')

Upvotes: 1

Bernhard
Bernhard

Reputation: 3694

The Matlab function fileparts might be want you want

fileparts - Parts of file name and path

This MATLAB function returns the path name, file name, and extension for the specified file.

[pathstr,name,ext] = fileparts(filename)`

For your case:

[pathstr,name,ext] = fileparts('filename.jpg.mat')
pathstr =
 ''
name =
filename.jpg
ext =
.mat

And then you can work with name and ext to your liking.

Upvotes: 0

Related Questions