1

I want to replace the & from the url which come after ? i.e query string.

Example
http://stackoverflow.com&/questions/ask?a=abcd&b=bcd&-------->1

Suppose there is a Url as 1 Now I want to replace the amp; with ""

http://stackoverflow.com&/questions/ask?a=abcd&b=bcd&-------->2

I have tried this regex as

\?(.*?&(amp;).*?){1,} for using Regex.Replace(......);

I want to replace group[2] with "". How to do that??????????

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125

2 Answers2

0

You can use this:

string pattern = @"((?:\?|\G(?<!^))(?:[^&]+|&(?!amp;))*&)amp;";
string replacement = "$1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

Pattern details:

(                         # capturing group: content after ? and before &amp; 
    (?:                   # non capturing group: entry point
        \?                # literal ?
      |                   # OR
        \G(?<!^)          # a match contiguous to a precedent match
    )
    (?:[^&]+|&(?!amp;))*  # all that is not a & or a & not followed by "amp;"
&                         # literal & before "amp;"
)
amp;
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

You probably don't want to replace amp; by nothing, but &amp; by &.

I suppose Regex is not the correct thing to use here. See Get url parameters from a string in .NET on how to extract parameters from a URL. This will automatically convert &amp; to &

Community
  • 1
  • 1
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222