Regular expressions Get URL parameters __ Regular expressions

Source: Internet
Author: User

In the work need to take the parameters in the URL, a lot, think of writing an expression.

C # version:

String url = "http://url/default.aspx?sname=sd&articleid=76369635-2b9c-495e-a7ec-44bbb290991f&pagenum=2 &magid=156&rtype=next ";

Regex Urlregex = new Regex (?: ^| /?| &) pagenum= ([^&]*) (?: &|$) ");
Match m = urlregex.match (URL. ToLower ());
String pagenum = String. Empty;
if (m.success)
{
Pagenum = m.groups[1]. Value;
}

JS Version (EXT):

function Geturlparam (name) {
var reg = new RegExp ("(^|&)" + name + "= ([^&]*) (&|$)");
var r = window.location.search.substr (1). Match (REG);
if (r!=null) {
Return unescape (r[2]);
}
return null;
}

Alert (Geturlparam ("Id"));


If the current URL is http://localhost/test/Untitled-11.html?Id=12456, then the function returns 12456,

Regular expression "(^|&)" + name + "= ([^&]*) (&|$)" is the key to this function

The return value of the function, R[2], represents the second match in the regular expression ([^&]*). Why "([^&]*)" can match 12456.

The [^xyz] negative character set is combined according to the syntax of the regular expression. Matches any characters that are not included. For example, ' [^ABC] ' can match ' P ' in ' plain '. "[^&]*" is 0 or more any character other than "&".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.