codelove
codelove

Reputation: 2016

Regex to get string in URL before optional character

I have a URL which may be formatted like this: http://domain.com/space/all/all/FarmAnimals

or like this: http://domain.com/space/all/all/FarmAnimals?param=2

What regular expression can I use to return the expression FarmAnimals in both instances?

I am trying this:

var myRegexp = /\.com\/space\/[a-zA-Z0-9]*\/[a-zA-Z0-9]*\/(.*)/;
var match = myRegexp.exec(topURL);
var full = match[1];

but this only works in the first instance, can someone please provide an example of how to set up this regex with an optional question mark closure?

Thank you very much!

Upvotes: 2

Views: 2948

Answers (5)

Wrikken
Wrikken

Reputation: 70490

 /[^/?]+(?=\?|$)/

Any non-/ followed by either ? or and end-of-line.

Upvotes: 5

keyboardP
keyboardP

Reputation: 69372

I wouldn't write my own regex here and let the Path class handle it (if those are your two string formats).

string url = "http://domain.com/space/all/all/FarmAnimals";

//ensure the last character is not a '/' otherwise `GetFileName` will be empty
if (url.Last() == '/') url = url.Remove(url.Length - 1);

//get the filename (anything from FarmAnimals onwards)
string parsed = Path.GetFileName(url);

//if there's a '?' then only get the string up to the '?' character
if (parsed.IndexOf('?') != -1) 
    parsed = parsed.Split('?')[0];

Upvotes: 2

femtoRgon
femtoRgon

Reputation: 33341

This

.*\/(.*?)(\?.*)?$

Should capture the part of the string you are looking for as the group 1 (and the query after ? in group 2, if needed).

Upvotes: 1

Adidi
Adidi

Reputation: 5253

var url = 'http://domain.com/space/all/all/FarmAnimals?param=2';
//var url = 'http://domain.com/space/all/all/FarmAnimals';
var index_a = url.lastIndexOf('/');
var index_b = url.lastIndexOf('?');
console.log(url.substring(index_a + 1, (index_b != -1 ? index_b : url.length)));

Upvotes: 0

tckmn
tckmn

Reputation: 59283

You could use something like this:

var splitBySlash = topURL.split('/')
var splitByQ = splitBySlash[splitBySlash.length - 1].split('?')
alert(splitByQ[0])

Explanation:

splitBySlash will be ['http:','','domain.com', ... ,'all','FarmAnimals?param=2'].

Then splitByQ will grab the last item in that array and split it by ?, which becomes ['FarmAnimas','param=2'].

Then just grab the first element in that.

Upvotes: 1

Related Questions