正则表达式:匹配文本到最后一个字符索引

时间:2011-08-31 19:47:15

标签: regex http

例如:

  

http://foobar.com/foo/bar/foobar.php

从这个地址,我需要提取以下内容:

  

http://foobar.com/foo/bar

我尝试过以下正则表达式:

(?<namespace>.*)/.*?

但返回的值是

  

HTTP:

有人可以帮忙吗?感谢。

3 个答案:

答案 0 :(得分:3)

试试这个:

^(?<namespace>.*)/[^/]+$

快速解释:

^                    # the start of input
(?<namespace>.*)/    # zero or more chars followed by a '/' (which the last '/') 
[^/]+                # one or more chars other than '/'
$                    # the end of input

答案 1 :(得分:2)

我认为正则表达式在这里是过度的。你使用什么编程语言?这将是它在JavaScript中的完成方式。

var url = 'http://foobar.com/foo/bar/foobar.php'
url.split('/').slice(0,-1).join('/')

你甚至可以使用 substr 来获得一些性能!

var url = 'http://foobar.com/foo/bar/foobar.php'
url.substr(0, url.lastIndexOf('/'))

我提供阵列方式的唯一原因是因为我不确定lastIndexOf上的浏览器兼容性。

答案 2 :(得分:0)

尝试使用此表达式:

^(?<namespace>.*)/.*$
相关问题