2013-02-26 81 views
1

在Javascript中,我正在尋找將URI轉換爲Windows格式的正則表達式,但我不太熟悉構成正則表達式的URI情況。 基本上...將URI轉換爲Windows路徑格式

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

應改爲

"C:\myDocs\file.txt" 

有可能是我不知道的其他情況。因此需要一些幫助。到目前爲止,我只用交換替換了斜線,而不是用正則表達式替換了驅動名稱。

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

正則表達式嚮導,請啓動您的引擎!

+0

嘿人,我的解決方案是正則表達式(按要求),並應付所有驅動器也,並張貼過。你爲什麼不喜歡它?並且是一個oneliner(與methode鏈接,但仍然可以) – 2013-02-26 15:04:11

回答

1

我假設C盤贏」 t是你的路徑字符串中唯一的驅動器,所以寫了一個模擬你的小型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; 
}
2

這將涵蓋兩種情況以上:

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

+1 Nice功能在替換函數中調用! *我喜歡* – 2013-02-26 12:55:31

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\,因此很明顯一個簡單的轉換在這裏不起作用。

+0

-1,因爲正則表達式搜索不是Js-Code – 2013-02-26 12:53:30

+1

他來這裏尋求建議,他得到了我最好的。他描述了一個問題,我給了他一個解決方案。在我看來,沒有必要降低這一點。如果他能夠提出一個合理的論點,說明他爲什麼需要*正則表達式......很好,但到目前爲止,我看不到這一點。 – 2013-02-26 12:55:11

+1

好吧,我在那裏頂了一下。對不起,今天咖啡太多了。 :) – 2013-02-26 12:57:23

1

這個表達式應該可以解決你的問題,但可以優化 負責所有驅動器名稱的長度爲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" 
相關問題