2014-01-20 118 views
1

在R,正則表達式匹配反斜線

我有以下字符串:C:\\Users\\jam\\Downloads\\tomato\\roja.exe 及以下的正則表達式:^(.*\\\\)([^\\\\]*)$

從此我想要的文件夾路徑:C:\\Users\\jam\\Downloads\\tomato\\

如果我這樣做grep像:

grep("^(.*\\\\)([^\\\\]*)$", "C:\\Users\\jam\\Downloads\\tomato\\roja.exe",value=TRUE) 

我得到C:\\Users\\jam\\Downloads\\tomato\\roja.exe結果是不是預期的結果。

關於提高正則表達式的任何想法?

+0

剛剛'^(。* \\\\)' – MElliott

+0

@MElliott nope不能正常工作 – umbersar

回答

3

無需使用正則表達式,嘗試dirname

dirname(" C:\\Users\\jam\\Downloads\\tomato\\roja.exe") 
" C:/Users/jam/Downloads/tomato" 

basename獲取文件名:

basename(" C:\\Users\\jam\\Downloads\\tomato\\roja.exe") 
[1] "roja.exe" 

編輯

使用正則表達式,我會使用類似這個:

gsub('(.*)[\\](.*)','\\1' ,"C:\\Users\\jam\\Downloads\\tomato\\roja.exe") 
[1] "C:\\Users\\jam\\Downloads\\tomato" 

gsub('(.*)[\\](.*)','\\2' ,"C:\\Users\\jam\\Downloads\\tomato\\roja.exe") 
[1] "roja.exe" 
+0

那麼有幫助但不能解決問題。 dirname返回無效的窗口上帶'/'字符的路徑。 – umbersar

+1

@wanderer在R中,它們是有效的。 –

+0

謝謝@MatthewLundberg。在窗口中的路徑中的「/」字符在R. – umbersar