0

I have an url like localhost:8001/?page=categories&catid=4&p=1888&country=1,2,3,6 and I want to remove &p=1888 part with regular expression. How can I match & exclude this part with asp.net c#?

Edit: Here is the function I've created for solution:

public string RemoveUrlParameters(HttpContext Context, string[] Parameters)
{
    string result = String.Empty;

    UriBuilder urlBuilder = new UriBuilder(Context.Request.Url.AbsoluteUri);
    var values = HttpUtility.ParseQueryString(urlBuilder.Query);

    for (int i = 0; i < Parameters.Length; i++)
        values.Remove(Parameters[i]);

    urlBuilder.Query = values.ToString();
    result = urlBuilder.ToString();
    result = Context.Server.UrlDecode(
    result.Replace("http://" + Context.Request.Url.Authority, String.Empty)
    .Replace(":80", String.Empty).Replace("default.aspx", String.Empty));

    return result;
}

2 Answers 2

9

I want to remove &p=1888 part with regular expression

I would recommend you to use url parsers, to avoid fragility of your code and guarantee that it will work for any valid url 100% of the cases because they respect the RFCs:

var url = "http://localhost:8001/?page=categories&catid=4&p=1888&country=1,2,3,6";
var urlBuilder = new UriBuilder(url);
var values = HttpUtility.ParseQueryString(urlBuilder.Query);
values.Remove("p");
urlBuilder.Query = values.ToString();
var newUrl = urlBuilder.ToString();

Implementing a valid URL parser with Regex could be quite challenging and not worth it especially when the .NET framework already provides you the tools to manipulate urls.

Sign up to request clarification or add additional context in comments.

Comments

0
Regex.Replace(input, @"&p=1888(?=&|$)", string.Empty)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.