Matlab正则表达式:如何在路径

时间:2017-04-28 01:09:22

标签: regex matlab

我需要获取文件夹名称,如下所示:

etc/my/folder/john/is/good

我想要“约翰”。

文件夹并且始终是静态的(相同)。在这个例子中,“john”可以是“jack”或其他名称。

由于

3 个答案:

答案 0 :(得分:1)

一种选择,使用positive lookaheads and lookbehinds查找一个或多个字母数字字符([a-zA-Z_0-9]):

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

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

返回:

test =

    'john'

根据您的表现需求,您也可以只使用前瞻,只使用外观,或两者都不使用。理论上,正则表达式执行的步骤越多,它就越慢。在这种情况下,您很可能不会注意到,但这是一个潜在的考虑因素。

例如:

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

返回与上面相同的内容。请注意,'tokens' outkey将返回一个单元格数组,我们可以根据需要获取字符数组。

我强烈建议您使用Regex101等网站作为游乐场来试验正则表达式并实时查看结果。

答案 1 :(得分:0)

您也可以使用regexp代替strfindstrfind可能更快,但在动态解决方案方面的能力较弱。你将使用你正在寻找的字符串在第3和第4个'/'之间的知识。

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

答案 2 :(得分:0)

使用新的replace函数(MATLAB2016b和更新版本),这是微不足道的:

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