Lanti
Lanti

Reputation: 2339

Match everything until last presence of a character

I have the following URL structure:

http://domain.com/images/1/10/104/104901/7.jpg

How can I match this with regex only until the last / slash to return this one?

http://domain.com/images/1/10/104/104901/

Thank You for your help!

Correction: I use Javascript.

Upvotes: 1

Views: 413

Answers (3)

Roy
Roy

Reputation: 41

It will depend on the language.

But for Python you might be able to get away with a regex of .+/

But that's just a quick test (I won't guarantee the robustness of it).

Here is it in action (regex101).

With a slight change you can get it to pass the regular expression site you were using.

.+\/

Alternatively, if you don't want to use regular expressions, you could just mirror the string and find that first slash as others have suggested.

Upvotes: 2

Aaron
Aaron

Reputation: 24822

An ES6 alternative without use of regular expressions would be to use String.prototype.substring and String.prototype.lastIndexOf :

myString.substring(0, myString.lastIndexOf('/'))

So, why should you use that ?

var myString = 'http://domain.com/images/1/10/104/104901/7.jpg';
console.time("With regex");
console.log(myString.replace(/[^/]+$/, ''));
console.timeEnd("With regex");                   // outputs 0.94ms
console.time("With String methods");
console.log(myString.substring(0, myString.lastIndexOf('/')));
console.timeEnd("With String methods");          // outputs 0.53ms

Benchmark done on Firefox on my computer, but results should be similar everywhere.

Upvotes: 2

anubhava
anubhava

Reputation: 786299

In Javascript you can use greedy match for this to match till last /:

/^.+\//

RegEx Demo

Alternatively you can do replacement of part after last /:

var s = 'http://domain.com/images/1/10/104/104901/7.jpg'
var r = s.replace(/[^/]+$/, '')
//=> "http://domain.com/images/1/10/104/104901/"

Upvotes: 2

Related Questions