2012-10-22 38 views
0

我SRC:使用reg exp我該如何替換文件名?

Video/webm/Task_2.4a_Host_treated.webm 

Video/ogv/Task_2.4a_Host_treated.theora.ogv 

Video/MP4/Task_2.4a_Host_treated.mp4 

我需要單獨更換(Task_2.4a_Host_treated.theora或Task_2.4a_Host_treated)領域?如何使用reg.exp來做到這一點?

回答

0

Working demo.

這個正則表達式將匹配最後一個正斜槓之後的一切,捕捉自己的組擴展,所以當我們做了更換,可以放回原位:

var regex = /\/[^/]*?(\.[^/.]*)?$/mg; 

現在,你可以用更換(其中$1指捕獲組,即文件擴展名):

str = str.replace(regex, '/whatyouwanttohaveinstead$1'); 

請注意,我使用m修改器來打開多線模式。由於這個$匹配每行的結尾(除了字符串的結尾)。

正則表達式的部分的一些解釋:

\/   # matches a literal slash 
[^/]*  # matches arbitrarily many non-slash characters 
?   # makes the previous repetition ungreedy, so it does not consume the 
      # file extension if there is one 
(   # starts a capturing group, which can be accessed later with $1 
\.   # matches a literal period 
[^/.]*  # matches as many non-period/non-slash characters as possible 
)   # closes the capturing group 
?   # makes the file extension optional 
$   # matches the end of the string, and due to the "m" modifier later 
      # the end of every line 

由於沒有這些字符可以是/我們錨比賽進行到字符串的結尾與$,這隻會是後一切最後的斜線。請注意,我還在文件擴展名的負面字符類中包含/。否則,您可能會遇到包含句點和文件但沒有文件擴展名的目錄的問題(在test/directory.containing.dots/file中,您會匹配第一個斜槓後的所有內容)。

0

試試這個:工作演示http://jsfiddle.net/Xnzmd/http://jsfiddle.net/Etbyg/1/

希望它適合事業:)

代碼

var file = "Video/ogv/Task_2.4a_Host_treated.theora.ogv"; 

extension = file.match(/\.[^.]+$/); 
filename = file.match(/(.*)\.[^.]+$/); 
alert('extention = '+extension); 
alert('Filename = ' + filename[1])​ 
0

我對你的問題有點困惑,所以我不確定你想要做什麼。如果要替換的文件名,使用此:如果要提取的文件名,擺脫一切的

var newpath = filepath.replace(/[^/]*(?=\.\w+$)/, 'replacement'); 

,試試這個:

var filename = filepath.replace(/.*\/|\.\w+$/g, ''); 
+0

這將刪除所有斜線和文件擴展名,導致'VideowebmTask_2.4a_Host_treated'。請測試您的解決方案。 –

+0

@ m.buettner - 這正是我想要做的。是什麼讓你認爲這是錯誤的行爲?也許我對這個問題感到困惑。 –

+0

我讀這個問題的方式,他想要替換文件名(沒有擴展名)。我無法讀取任何關於連接所有目錄名稱與文件名稱的任何信息。 –