2011-12-24 48 views
0

我試圖在正則表達式中創建一個新的文件路徑,以便移動一些文件。說我有以下路徑:使用正則表達式創建新的文件路徑

c:\Users\User\Documents\document.txt 

我想將其轉換爲:

c:\Users\User\document.txt 

有沒有一種簡單的方法在正則表達式來做到這一點?

+0

你使用什麼語言,你確定要使用正則表達式嗎? – 2011-12-24 17:05:13

+1

它是否總是與你想要做的相同的轉換,即刪除路徑中的最後一個目錄?它應該只在Windows上工作,還是應該在其他操作系統上工作?答案取決於所有這些。特別是如果你有Cygwin,存在的工具可以讓你不使用regexes。 – fge 2011-12-24 17:20:44

+0

我正在使用C#。它本身不一定是正則表達式,但我通過正則表達式可能爲這個問題提供了一個乾淨的解決方案。每次轉換都是一樣的,即我正在使用固定的文件夾結構。對正則表達式的支持並不重要,它不是一個將廣泛分發的應用程序:) – Daan 2011-12-24 17:47:48

回答

1

如果你需要的是從文件的路徑,然後我認爲這將是更容易使用,而不是內置FileInfoDirectoryInfoPath.Combine正則表達式去除這裏的最後一個文件夾名稱:

var fileInfo = new FileInfo(@"c:\Users\User\Documents\document.txt"); 
if (fileInfo.Directory.Parent != null) 
{ 
    // this will give you "c:\Users\User\document.txt" 
    var newPath = Path.Combine(fileInfo.Directory.Parent.FullName, fileInfo.Name); 
} 
else 
{ 
    // there is no parent folder 
} 
+0

是的,你說得對。這可能比使用正則表達式更容易。 – Daan 2012-01-11 18:36:01

1

Perl正則表達式的一種方式。它刪除該路徑的最後一個目錄:

s/[^\\]+\\([^\\]*)$/$1/ 

說明:

s/.../.../   # Substitute command. 
[^\\]+    # Any chars until '\' 
\\     # A back-slash. 
([^\\]*)    # Any chars until '\' 
$      # End-of-line (zero-width) 
$1     # Substitute all characters matched in previous expression with expression between parentheses. 
+0

至少第一個'*'應該是一個'+',甚至是'++'(perl 5.8+) - 但是否則它只是做這個工作:p – fge 2011-12-24 17:42:27

+0

@fge:謝謝,我解決了它。 – Birei 2011-12-24 17:46:04

+0

感謝您的建議。我也可以在C#中使用它嗎? – Daan 2011-12-24 17:51:36

0

你可以試試這個,雖然它是一個Java代碼

String original_path = "c:\\Users\\User\\Documents\\document.txt"; 
String temp_path = original_path.substring(0,original_path.lastIndexOf("\\")); 
String temp_path_1 = temp_path.substring(0,temp_path.lastIndexOf("\\")); 
String temp_path_2 = original_path.substring(original_path.lastIndexOf("\\")+1,original_path.length()); 

System.out.println(temp_path_1 +"\\" + temp_path_2); 

你提到轉型是相同的每次如此,依靠regexp並不總是一個好的做法,可以使用String manipulations來完成。

0

爲什麼不能組合pathStr.Split('\\'),Take(length - 2)String.Join

0

使用正則表達式replace方法。找到你正在尋找的東西,然後用什麼都替換(string.empty)這裏是C#代碼:

string directory = @"c:\Users\User\Documents\document.txt"; 
string pattern = @"(Documents\\)"; 

Console.WriteLine( Regex.Replace(directory, pattern, string.Empty)); 

// Outputs 
// c:\Users\User\document.txt