Regex Matlab正则表达式:如何在路径中获取文件夹名称

Regex Matlab正则表达式:如何在路径中获取文件夹名称,regex,matlab,Regex,Matlab,我需要获得文件夹名称,如下所示: etc/my/folder/john/is/good 我要“约翰” 文件夹和始终是静态的(相同)。在本例中,“john”可以是“jack”或其他名字 感谢使用一个选项查找一个或多个字母数字字符([a-zA-Z_0-9]): 根据您的性能需要,您也可以只使用前向、后向或两者都不使用。理论上,正则表达式执行的步骤越多,执行的速度就越慢。在这种情况下,您很可能不会注意到,但这是一个潜在的考虑因素 例如: exp2 = 'folder\/(\w+)\/is'; tes

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

etc/my/folder/john/is/good
我要“约翰”

文件夹和始终是静态的(相同)。在本例中,“john”可以是“jack”或其他名字

感谢使用一个选项查找一个或多个字母数字字符(
[a-zA-Z_0-9]
):

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

例如:

exp2 = 'folder\/(\w+)\/is';
test2 = regexp(mystr, exp2, 'tokens', 'once');
test2 = test2{:}
返回与上面相同的值。注意,将返回一个单元格数组,我们可以根据需要使用最密集的单元格数组来获取字符数组


我强烈建议使用类似于游乐场的站点来试验正则表达式,并实时查看结果。

您也可以使用
strfind
而不是
regexp
strfind
可能更快,但在动态解决方案方面的能力较差。您将使用查找的字符串介于第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

使用新的
replace
功能(MATLAB2016b及更新版本),这是一个微不足道的问题:

a='etc/my/folder/john/is/good';
b=replace(a, {'etc/my/folder/','/is/good'},'');
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
a='etc/my/folder/john/is/good';
b=replace(a, {'etc/my/folder/','/is/good'},'');