2012-08-25 48 views
0

我有一個字符串,它看起來像這樣:"http://www.example.com/hello/world/ab/c/d.html"(或本:"http://www.example.com/hello/world/ab/d.html"JavaScript正則表達式來提取中間部分

我想提取http://www.example.com/hello/world/d.html之間的內容。通用正則表達式應該是什麼?

+0

取決於你所說的 '中間' 是什麼。在這種情況下,你需要第三和第四個路徑組件 - 幾乎不是中間的「通用」定義。 – nneonneo

+0

只是'http://xxx/xxx/xxx'和'xxx.html'之間的組件 – mmcc

回答

1

你可能想

/^http:\/\/[^\/]*\/[^\/]*\/[^\/]*\/(.*)\/[^\/]*$/ 

這(複雜的前瞻性)表達跳過域和前兩個路徑組件,然後提取最終路徑組件之前,所有位。

例子:

>>> 'http://www.google.com/hello/world/ab/c/d.html'.match(/^http:\/\/[^\/]*\/[^\/]*\/[^\/]*\/(.*)\/[^\/]*$/) 
["http://www.google.com/hello/world/ab/c/d.html", "ab/c"] 
0

你正在尋找的正則表達式是這樣的:/^http\://www.google.com/hello/world/(.*/)d.htm$/

http://jsfiddle.net/rDvJK/

function getIt(fromWhat) { 
    var matches = fromWhat.match(/^http\:\/\/www\.google\.com\/hello\/world\/(.*\/)d.htm$/); 
    console.log(matches); 
    return matches[1]; 
} 
getIt("http://www.google.com/hello/world/ab/c/d.htm");