How To Parse A URL into sections in ASP.NET Using Pattern Matching

I am trying to find a way to parse a URL in the Global.asax file in ASP.NET into sections.

Given the example of: http://www.site.com/OptionalFirstURLSection/Pages/PageKey I need to find a way to capture the PageKey (maybe using a regular expression) in these scenarios:
The folder Pages exists in the URL string followed by some value –
PageKey from the following
http://www.site.com/Pages/PageKey
http://www.site.com/Pages/PageKey/ (trailing slash)
http://www.site.com/Something/Pages/PageKey
http://www.site.com/Something/Something/Something/Pages/PageKey
endrecAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
SiliconXPConnect With a Mentor Commented:
hi

try this.
string pageKey=string.Empty;
			string str=@"http://www.site.com/Something/Something/Something/pages/PageKey4/";
			if(str.ToLowerInvariant().Contains("/pages/"))
			   {
			if(str.EndsWith("/")) str=str.Remove(str.Length-1,1);
			pageKey=str.Remove(0,str.LastIndexOf("/")+1);
}
			
			

Open in new window

0
 
rajeeshmcaConnect With a Mentor Commented:
hi endrec,

Try the following :

aspx page
-----------------

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" src="scripts/jquery-1.3.2.js" ></script>
    <script type="text/javascript" src="scripts/jquery.timeentry.js" ></script>
    <script type="text/javascript">
        $(function () {
            $('#TimeTextbox').timeEntry({spinnerImage: ''});
            });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="TimeTextbox" runat="server"></asp:TextBox>
     <asp:TextBox ID="StringTextBox" runat="server"></asp:TextBox>
     <asp:Button ID="Button1" runat="server" Text="Test" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>

cs page
------------

protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string pageKey = string.Empty;
        pageKey = StringTextBox.Text.Substring(StringTextBox.Text.IndexOf("PageKey", StringComparison.OrdinalIgnoreCase));
        if(pageKey.IndexOf("/") != -1)
            pageKey = pageKey.Substring(0, pageKey.IndexOf("/"));
        Response.Write(pageKey);
    }
0
All Courses

From novice to tech pro — start learning today.