2

在 Javascript 中,我正在寻找将 URI 转换为 Windows 格式的正则表达式,但我不太熟悉 URI 案例以形成正则表达式。基本上...

  • /c/myDocs/file.txt
  • //myDocs/file.txt

应该改为

"C:\myDocs\file.txt"

可能还有其他我不知道的情况。因此需要一些帮助。到目前为止,我所拥有的只是用替换替换斜杠,而不是用正则表达式交换驱动器名称。

function pathME(apath)
{
    apath = apath.replace(/\//g, "\\")
    return apath;
}

正则表达式向导,请启动您的引擎!

4

4 回答 4

4

这将涵盖上述两种情况:

mystring.replace(/^\/([^\/]?)\//, function(match, drive) {
    return (drive || 'c').toUpperCase() + ':\\';
}).replace(/\//g, '\\');
于 2013-02-26T12:36:22.523 回答
2

此正则表达式应该可以解决您的问题,但可以进行优化 处理长度为 1 的所有驱动器名称:

   "/c/myDocs/file.txt".replace(/\//g,"\\").replace(/^(\\)(?=[^\\])/, "").replace(/^(\w)(\\)/g, "$1:\\")
  // Result is "c:\myDocs\file.txt"

示例二

"//myDocs/file.txt".replace(/\//g,"\\").replace(/^(\\)(?=[^\\])/, "").replace(/^(\w)(\\)/g, "$1:\\")
 // Result is "\\myDocs\file.txt"
于 2013-02-26T12:48:03.997 回答
1

我假设 C 驱动器不会是您的路径字符串中的唯一驱动器,因此编写了一个模仿您的小型 pathME() 函数。这应该涵盖您提到的所有情况。

function pathME(apath) {
    //Replace all front slashes with back slashes
    apath = apath.replace(/\//g, "\\");

    //Check if first two characters are a backslash and a non-backslash character
    if (apath.charAt(0) === "\\" && apath.charAt(1) !== "\\") {
        apath = apath.replace(/\\[a-zA-Z]\\/, apath.charAt(1).toUpperCase() + ":\\");
    }

    //Replace double backslash with C:\
    apath = apath.replace("\\\\", "C:\\");
    return apath;
}
于 2013-02-26T13:24:17.863 回答
0

这里不需要任何正则表达式。您可以通过简单的字符串操作来做到这一点:我认为。这样,如果您愿意,您可以更好地处理输入字符串中的错误。

var newpath = apath.replace(/\//g, '\\');
var drive = null;
if (newpath.substring(0, 2) == '\\\\') { 
   drive = 'c';
   newpath = newpath.substring(1);
}
else if (newpath.substring(0, 1) == '\\') {
   drive = newpath.substring(1, newpath.indexOf('\\', 2)); 
   newpath = newpath.substring(newpath.indexOf('\\', 2));
}
if (drive != null) { newpath = drive + ':' + newpath; }

附带说明:我不知道您的问题的范围,但是在某些情况下这不起作用。例如,在 Unix 中,网络共享会被挂载到,/any/where/in/the/filesystem而在 Windows 中,您需要\\remotehost\share\,因此显然简单的转换在这里不起作用。

于 2013-02-26T12:41:11.570 回答