开发者

Regular expressions: Matching text up to last index of character

For example:

http://foobar.com/foo/bar/fooba开发者_高级运维r.php

From this address, I need to extract the following:

http://foobar.com/foo/bar

I have tried with the following regex:

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

but returned value is

http:

Can anyone help? Thanks.


Try this:

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

A quick explanation:

^                    # 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


I think a regex is overkill here. What programming language are you using? This would be how it's done in JavaScript.

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

You could even use substr for some performance!

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

The only reason I offered the array way is because I'm not sure of cross browser compatibility on lastIndexOf.


Try with this expression:

^(?<namespace>.*)/.*$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜