javascript正则表达式提取中间部分

时间:2012-08-25 05:07:46

标签: regex

我有一个如下所示的字符串:"http://www.example.com/hello/world/ab/c/d.html"(或者这个:"http://www.example.com/hello/world/ab/d.html"

我想在http://www.example.com/hello/world/d.html之间提取内容。泛型正则表达式应该是什么?

2 个答案:

答案 0 :(得分: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"]

答案 1 :(得分: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");