replace matching special characters pattern from a string

时间:2015-09-01 22:42:26

标签: c# asp.net

string s = "apple]","[banana...." ;

I need to remove ( "]","[ ) and replace with "," from above string so that the output looks like below:

s = "apple,banana...."

s = s.Replace(@"\]","[\", ",");  //something like this?

2 个答案:

答案 0 :(得分:1)

You need to escape the quotation marks in the string. You have tried to escape something, but \ isn't used to escape characters in a @ delimited string.

In a @ delimited string you use "" to escape ":

s = s.Replace(@"]"",""[", ",");

In a regular string you use \" to escape ":

s = s.Replace("]\",\"[", ",");

答案 1 :(得分:0)

I assume it is a string[]?

I propose something like this:

    string[] s = {"[apple]","[banana]","[orange]"} ;
    string new_s = "";
    foreach (string ss in s)
    {                
        new_s += ss.Replace("[", "").Replace("]", ",");                
    }

    //handle extra "," at end of string
    new_s = new_s.Remove(new_s.Length-1);

Edit: Disregard, I misunderstood what you were trying to accomplish due to syntactical errors in your string definition.

string s = "apple]","[banana...." ;

should be:

string s = "apple]\",\"[banana....";