Reputation: 144
I have a bring string of say 2000 characters. I want to search for particular pattern and then replace the part of that pattern.
the string is as follows:
data = "additional data \"StartDate\":\"20141101\" additonal data additional data"
Is there a way to change the value 20141101 with some other value say 20121212 that is near to startdate. I am facing issues with double quotes that are near to the search pattern.
Upvotes: 0
Views: 82
Reputation: 111940
Some possible solutions:
string data = "additional data \"StartDate\":\"20141101\" additonal data additional data";
The one I would use: it uses zero-width assertions to "match" the "StartDate":"
and the final "
:
string data2 = Regex.Replace(data, "(?<=\"StartDate\":\")([0-9]{8})(?=\")", "xxxxxxxx");
The "simple" solution: it matches \"StartDate\":\"20141101\"
and replaces with \"StartDate\":\"xxxxxxxx\"
string data3 = Regex.Replace(data, "\"StartDate\":\"[0-9]{8}\"", "\"StartDate\":\"xxxxxxxx\"");
Another solution, based on using the special replacers $1
, $3
, that are the strings captured in the first and third capture group (the (...)
)
string data4 = Regex.Replace(data, "(\"StartDate\":\")([0-9]{8})(\")", "$1xxxxxxxx$3");
Upvotes: 1
Reputation: 462
if the value is always numeric:
var data = "additional data \"StartDate\":\"20141101\" additonal data additional data";
var num = new Regex("StartDate.+?(\\d+)").Match(data).Groups[1].Value;
Console.WriteLine(data.Replace(num, "20121212"));
Upvotes: 0