Dipole
Dipole

Reputation: 1910

How to split Matlab string into two with known suffix?

I need to split a string into two components. As an example I have the string:

s = 'Hello1_1000_10_1_data'

and I want to split it into the two strings

str1 = 'Hello1_1000_10_1'

and

str2 = '_data'

the important point is that I can't be too sure of the format of the first string, the only thing that is sure is that the 'suffix' which is to be read into the second string always reads '_data'. What is the best way to do this? I looked up the documentation on strtok and regexp but they do not seem to offer me what I want.

Upvotes: 1

Views: 378

Answers (4)

Nras
Nras

Reputation: 4311

You can use strfind():

s = 'Hello1_1000_10_1_data';
suffix = '_data';
i = strfind(s,suffix);
if any(i)
    i = i(end);
    prefix = s(1:i-1);
end

Upvotes: 0

nicolas
nicolas

Reputation: 3280

You can use:

s = 'Hello1_1000_10_1_data';

str = regexp(s, '(.*)(_data)', 'tokens'){1};
str{1}    %//     Hello1_1000_10_1
str{2}    %//     _data

If _data occurs several times in the file name, this will still work.

Upvotes: 1

Nematollah Zarmehi
Nematollah Zarmehi

Reputation: 694

You can also use strsplit() as follow:

s = 'Hello1_1000_10_1_data';
suffix = '_data';
str = strsplit(s,suffix);
str1 = str{1}

In addition, you can use strsplit() with multiple delimiters.

Upvotes: 0

Matt Swain
Matt Swain

Reputation: 3887

If you always know the length of the suffix, you could just use that:

s = 'Hello1_1000_10_1_data'
str1 = s(1:end-5)

Or otherwise:

s = 'Hello1_1000_10_1_data'
suffix = length('_data')
str1 = s(1:end-suffix)

Upvotes: 3

Related Questions