简体   繁体   中英

Matlab regex: how to grab a folder name in path

I need to get the folder name as follows:

etc/my/folder/john/is/good

I want "john".

folder and is are always static (same). Just that "john" can be "jack" or other names, in this example.

Thanks

One option, using positive lookaheads and lookbehinds to look for one or more alphanumeric characters ( [a-zA-Z_0-9] ):

mystr = 'etc/my/folder/john/is/good';
exp1 = '(?<=folder\/)(\w+)(?=\/is)';

test = regexp(mystr, exp1, 'match', 'once')

Which returns:

test =

    'john'

You could also use just the lookahead, just the lookbehind, or neither, depending on your performance needs. In theory, the more steps the regex has to perform the slower it will be. You very likely won't notice in this case, but it is a potential consideration.

For example:

exp2 = 'folder\/(\w+)\/is';
test2 = regexp(mystr, exp2, 'tokens', 'once');
test2 = test2{:}

Returns the same as above. Note that the 'tokens' outkey will return a cell array, which we can denest as necessary to obtain a character array.

I would highly recommend using sites like Regex101 as a playground to experiment with regular expressions and see the results in real time.

Instead of regexp you could also use strfind . strfind is likely to be faster, but is less capable in terms of dynamic solutions. You'll use the knowledge that the string you are looking for is between the 3rd and the 4th '/'-character.

folder='etc/my/folder/john/is/good';
positions=strfind(folder,'/'); % get positions of the slashes
name=folder(positions(3)+1:positions(4)-1) % output the string between the 3rd and 4th slash

With the new replace function (MATLAB2016b and newer), this is trivial:

a='etc/my/folder/john/is/good';
b=replace(a, {'etc/my/folder/','/is/good'},'');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM