Ege Bayrak
Ege Bayrak

Reputation: 1199

Replacing characters between two characters

I'm trying to manipulate a string and I want to remove some characters in it.

Example scenario:

abc-def-c?p=2&x=5&z=6

I want to replace all chars starting from p and ending with the char after next & or ? with empty chars. Deleting them in a way.

Input: abc-def-c?p=2&x=5&z=6

Output: abc-def-c?x=5&z=6

I know I can achieve this with Substring ,IndexOf and Replace but sadly there is a problem that p,x,y parts may not be in this order all the time. I need something which would find just the part and replace it.

My regex skills are not that great so any help is appreciated.

Upvotes: 1

Views: 1407

Answers (3)

wikiCan
wikiCan

Reputation: 449

check input contains of p= like this example :

Method Shown

public static string cleanString(string input)
{
    if (input.Contains("p=") && input.Contains("&"))
    {
        int startPos = input.IndexOf("p=");
        int endPos = input.IndexOf("&",startPos);
        input = input.Substring(0,startPos) + 
                                       input.Substring(endPos+1,(input.Length-1)-endPos);
    }

    return input;
}

Usage

cleanString("abc-def-c?p=2&x=5&z=6"));
cleanString("abc-def-c?"));

Upvotes: 0

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

Try this regex:

(?<=[?&])p=.*?(?:&|$)

It matches p= preceded by ? or & ((?<=[?&])) and followed by a string value which terminates with either & or end of string ((?:&|$))

Demo

Upvotes: 2

Milney
Milney

Reputation: 6427

I do not like Regexs so as an alternative if you are the same, you could use the class posted in one of the answers to this question;

Get url parameters from a string in .NET

Which turns Query String into a Dictionary, and then just take all keys except the one you want to ignore...

Upvotes: 0

Related Questions