dmr
dmr

Reputation: 22333

Regex: find whatever comes after one thing before another thing

I want to find anything that comes after s= and before & or the end of the string. For example, if the string is

t=qwerty&s=hello&p=3

I want to get hello. And if the string is

t=qwerty&s=hello

I also want to get hello

Thank you!

Upvotes: 1

Views: 1042

Answers (4)

Dean Gurvitz
Dean Gurvitz

Reputation: 1072

You can also use the following expression, based on the solution provided here, which finds all characters between the two given strings:

(?<=s=)(.*)(?=&)

In your case you may need to slightly modify it to account for the "end of the string" option (there are several ways to do it, especially when you can use simple code manipulations such as manually adding a & character to the end of the string before running the regex).

Upvotes: 0

fge
fge

Reputation: 121712

\bs=([^&]+) and grabbing $1should be good enough, no?

edit: added word anchor! Otherwise it would also match for herpies, dongles...

Upvotes: 5

gereeter
gereeter

Reputation: 4761

The simplest way to do this is with a selector s=([^&]*)&. The inside of the parentheses has [^&] to prevent it from grabbing hello&p=3 of there were another field after p.

Upvotes: 1

sehe
sehe

Reputation: 392911

Why don't you try something that was generically aimed at parsing query strings? That way, you can assume you won't run into the obvious next hurdle while reinventing the wheel.

jQuery has the query object for that (see JavaScript query string)

Or you can google a bit:

function getQuerystring(key, default_)
{
   if (default_==null) default_=""; 
   key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
   var qs = regex.exec(window.location.href);
   if(qs == null)
     return default_;
   else
     return qs[1];
}

looks useful; for example with

http://www.bloggingdeveloper.com?author=bloggingdeveloper

you want to get the "author" querystring's value:

var author_value = getQuerystring('author');

Upvotes: 1

Related Questions