将URI转换为windows路径格式

Convert URI to windows path format

本文关键字:路径 格式 windows URI 转换      更新时间:2023-09-26

在Javascript中,我正在寻找一个将URI转换为Windows格式的正则表达式,但我不太熟悉URI的情况,无法形成正则表达式。大体上

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

应该改为

"C:'myDocs'file.txt"

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

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

Regex巫师,请启动引擎!

这将涵盖以上两种情况:

mystring.replace(/^'/([^'/]?)'//, function(match, drive) {
    return (drive || 'c').toUpperCase() + ':''';
}).replace(/'//g, '''');

这个Regex应该可以解决您的问题,但可以进行优化负责长度为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"

这里不需要任何正则表达式。你只需要简单的字符串操作就可以做到:,我想。这样你就可以更好地处理输入字符串中的错误,如果你愿意的话

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',因此很明显,简单的转换在这里不起作用。

我假设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;
}