Reputation: 3793
Suppose that we have these strings in MATLAB:
xx = 'C:/MY_folder/This_gg/microsoft/my_file';
or
xx = 'C:/end_folder/This_mm/google/that_file';
I want remove expression after end /
(my_file
and that_file
). How can I do this using regular expression in MATLAB?
Upvotes: 2
Views: 3202
Reputation: 163
Instead of regexp you can use fullfile, that is independent if there is '\' or '/'
yy = fullfile(xx, '..')
This returns the string 'xx\..'.
zz = fullfile(yy, 'newfolder')
This returns the string 'xx\..\newfolder' but it parses correctly on dir() and other functions.
Of course you can go back and forth in one line.
zz = fullfile(xx, '..', 'newfolder')
Upvotes: 1
Reputation: 71
If you want to remove last word try this:
yy = regexprep(xx,'(\w+)$','');
This find last word in the string and replaces it by empty string.
You can see the regex in following link: Regex101.com - Select last word
Upvotes: 1
Reputation: 112749
If you want to also remove the final /
, use
yy = regexprep(xx, '/[^/]*$', '');
The regexp pattern '/[^/]*$'
matches a /
followed by any number of non-/
at the end of the string. The match is replaced (regexprep
) by the empty string.
If you want to keep the final /
, you can modify the regexp with a lookbehind assertion:
yy = regexprep(xx, '(?<=/)[^/]*$', '');
or in 1 replace by '/'
instead of by ''
:
yy = regexprep(xx, '/[^/]*$', '/');
Upvotes: 1
Reputation: 5984
I know you're asking for a regular expression but there's a simpler way:
pathStr = fileparts(xx)
Or, if you want all parts of the file
[pathStr, name, ext] = fileparts(xx)
Upvotes: 3