user3711357 user3711357 - 2 years ago 102
C# Question

How to replace specific string in long string text

In below expression, I just need to replace
"pmcKey" field value with another string.
"pmcKey":"value....long" , need replace "value....long" with other string.
How to do this, by string.replace going very long way.

{"rd":"1404900091","d":"25994","dddd":99,"pmcKey":"95abcdefgiJBMjU2R0NNS1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiaXYiOiJBQVNNa0lsQ3l6blRsWktiIiwidGFnIjoiUlFuNUhVSWVHMVN0TmxJdXB5SGZNZyIsInppcCI6IkRFRiJ9.6zef568_zt8uZGlOdZZZga0FJV1CJcf-RdEIUk88ZtNyEmVX7eLnuce1nhkROgA03444LRiOxkFLFJ_eW5Um8w.k72DtsRbZzuTqWqOFlacVw.D3Sn9jiKRosZboqE0v999htZuyHu4Eukcq64Df5ga6XEOIOj6vDwR-2_NxzYs58kWpvP999SsXdYfqn1m9--h3lgcJEqOb2z4u_yXzxRWsGQe8kNwdWndFJox699999lQI0djiYAQtkhgqI6hgBS_muWiYar9WpP6K3fxPn99999cXlN6L0RdqWIl_U-wV5mlpMivxfyk0fMVcD1T9GTk99999aHpPPAYJ0pHIOYJjak2tj7J_nK4jPxrw7pNbQ3h2TB71JE5UTs4P9NgsL299999eb2wdJuOgJR9md-8PiGAJvWpgQSQu9HNvGowaTq.9999999991gjk0SQEXxfFBUTJKDANTdVBN52FURbIXQ","id":null,"req":null,"page":1,"CDate":null}

Answer Source

Assuming your input is valid Json you may try this code:

var input = "{\"rd\":\"1404900091\",\"d\":\"25994\",\"dddd\":99,\"pmcKey\":\"95abcdefgiJBMjU2R0NNS1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiaXYiOiJBQVNNa0lsQ3l6blRsWktiIiwidGFnIjoiUlFuNUhVSWVHMVN0TmxJdXB5SGZNZyIsInppcCI6IkRFRiJ9.6zef568_zt8uZGlOdZZZga0FJV1CJcf-RdEIUk88ZtNyEmVX7eLnuce1nhkROgA03444LRiOxkFLFJ_eW5Um8w.k72DtsRbZzuTqWqOFlacVw.D3Sn9jiKRosZboqE0v999htZuyHu4Eukcq64Df5ga6XEOIOj6vDwR-2_NxzYs58kWpvP999SsXdYfqn1m9--h3lgcJEqOb2z4u_yXzxRWsGQe8kNwdWndFJox699999lQI0djiYAQtkhgqI6hgBS_muWiYar9WpP6K3fxPn99999cXlN6L0RdqWIl_U-wV5mlpMivxfyk0fMVcD1T9GTk99999aHpPPAYJ0pHIOYJjak2tj7J_nK4jPxrw7pNbQ3h2TB71JE5UTs4P9NgsL299999eb2wdJuOgJR9md-8PiGAJvWpgQSQu9HNvGowaTq.9999999991gjk0SQEXxfFBUTJKDANTdVBN52FURbIXQ\",\"id\":null,\"req\":null,\"page\":1,\"CDate\":null}";
var json = JObject.Parse(input);
json["pmcKey"] = "other string";
var result = json.ToString();


EDIT If my assumption is wrong you can use regular expressions like this:

var regex = new Regex("\"pmcKey\":\"(?<oldValue>[^\"]+)\"");
var oldValue = regex.Match(input).Groups["oldValue"];
var newValue = "otherValue";
var result = $"{input.Substring(0, oldValue.Index)}{newValue}{input.Substring(oldValue.Index + oldValue.Length)}";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download