模式匹配webkitRelative中的第一个子目录

时间:2014-06-14 08:17:56

标签: javascript regex

基本上,我想模式匹配第一个目录文件夹或文件。

如何模式匹配两个或“/”之间的所有字符串。对于前。

我有这个清单:

Folder 1/File 2.avi
Folder 1/Folder2/File.avi
Folder 1/Folder2/Fils.mfg
Folder 1/Folder2/Folder 3/flag.gif

在此列表中,我希望输出为

Folder 1/File 2.avi
Folder 1/Folder2/

我刚开始使用javascript正则表达式并且丢失了。我的尝试非常糟糕

str.match(/\/[abc]\//)

谢谢你, JJ

1 个答案:

答案 0 :(得分:0)

<强> 1。使用正则表达式匹配路径

它们在您的文件中的方式,您可以使用它(请参阅demo):

^[^/]*/[^/\r\n]*/?

上面的正则表达式将匹配Folder 1/Folder2/三次,所以当你遍历匹配时,你只想添加那些不在数组中的那些。

<强> 2。仅添加匹配的路径(如果它不在结果数组中

在代码中,您可以将匹配项添加到数组中。请参阅online demo

<script>
var subject = 'Folder 1/File 2.avi \n \
Folder 1/Folder2/File.avi \n \
Folder 1/Folder2/Fils.mfg \n \
Folder 1/Folder2/Folder 3/flag.gif';
var unikmatches = []; // we will build this
var regex = /^[^\/]*\/[^\/\r\n]*\/?/mg;
var match = regex.exec(subject);
while (match != null) {
    // matched text: match[0]
    // only add if it is not yet in unikmatches
    if(unikmatches.indexOf(match[0]) < 0 ) { 
        unikmatches.push(match[0]);
        document.write(match[0],"<br>");
        }
    match = regex.exec(subject);
}
</script>

解释正则表达式

^                        # the beginning of the string
[^/]*                    # any character except: '/' (0 or more times
                         # (matching the most amount possible))
/                        # '/'
[^/\r\n]*                # any character except: '/', '\r' (carriage
                         # return), '\n' (newline) (0 or more times
                         # (matching the most amount possible))
/?                       # '/' (optional (matching the most amount
                         # possible))
相关问题