Regex: find whatever comes after one thing before another thing

后端 未结 4 559
南笙
南笙 2021-01-15 17:55

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

t=qwert

相关标签:
4条回答
  • 2021-01-15 18:07

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

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

    0 讨论(0)
  • 2021-01-15 18:15

    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.

    0 讨论(0)
  • 2021-01-15 18:16

    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).

    0 讨论(0)
  • 2021-01-15 18:19

    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');
    
    0 讨论(0)
提交回复
热议问题