| Snippet | Regular Expressions | Text and Strings | C# | .NET | Browsers | Web |
Example: Regular Expressions for Parsing URIs and URLsOK, we're finally here. The following method may be copied into the code behind file of your aspx page. Ensure there is a Label named lblOutput on your aspx page and call the TestParseURL method.
|
Example: Parse a URL with C# Regexpublic void TestParseURL()
{
string url = "http:
+ "/Cambia3/snippets/csharp/regex/uri_regex.aspx?id=17#authority";
string regexPattern = @"^(?<s1>(?<s0>[^:/\?#]+):)?(?<a1>"
+ @"//(?<a0>[^/\?#]*))?(?<p0>[^\?#]*)"
+ @"(?<q1>\?(?<q0>[^#]*))?"
+ @"(?<f1>#(?<f0>.*))?";
Regex re = new Regex(regexPattern, RegexOptions.ExplicitCapture);
Match m = re.Match(url);
lblOutput.Text = "<b>URL: " + url + "</b><p>";
lblOutput.Text +=
m.Groups["s0"].Value + " (Scheme without colon)<br>";
lblOutput.Text +=
m.Groups["s1"].Value + " (Scheme with colon)<br>";
lblOutput.Text +=
m.Groups["a0"].Value + " (Authority without //)<br>"
lblOutput.Text +=
m.Groups["a1"].Value + " (Authority with //)<br>"
lblOutput.Text +=
m.Groups["p0"].Value + " (Path)<br>";
lblOutput.Text +=
m.Groups["q0"].Value + " (Query without ?)<br>";
lblOutput.Text +=
m.Groups["q1"].Value + " (Query with ?)<br>";
lblOutput.Text +=
m.Groups["f0"].Value + " (Fragment without #)<br>";
lblOutput.Text +=
m.Groups["f1"].Value + " (Fragment with #)<br>";
} |
The following is the output you should see on your aspx page when you run the above method.
|
Example: OutputURL: http://www.cambiaresearch.com/Cambia3/snippets/csharp/
regex/uri_regex.aspx?id=17#authority
http (Scheme without colon)
http: (Scheme with colon)
www.cambiaresearch.com (Authority without //)
//www.cambiaresearch.com (Authority with //)
/Cambia3/snippets/csharp/regex/uri_regex.aspx (Path)
id=17 (Query without ?)
?id=17 (Query with ?)
authority (Fragment without #)
#authority (Fragment with #) |
|