Reputation: 2134
I need to replace all the occurrences of a sub-string with another string. But I do not want to replace the occurrence of a sub-string in a particular sub-string within the main string.
Example
string main = "The value for v and p are not v and p"
string replacestring= "v";
main = main.Replace(replacestring,12);
Result
main = The 12alue for 12 and p are not 12 and p
Expected Result
main =The value for 12 and p are not v and p.
So basically I am not trying to skip the first occurrence of the substring but the whole sub-string value
. I do not want it to be replaced for any value of replacestring
. I have tried to find the index of the first occurrence of the sub-string value
and skipping the next 4 characters and then replacing. But it isn't efficient enough for me as can have more than one occurrence of value
.
Upvotes: 1
Views: 158
Reputation: 627082
If you want to replace the first v
as a whole word, use
var rx1 = new Regex(@"\bv\b");
var t = rx1.Replace("The value for v and p are not v and p", "12", 1);
See Regex.Replace
method. The last 1
argument is count
(the maximum number of times the replacement can occur.)
The regex \bv\b
matches any v
that is enclosed with non-word characters (non-letters, non-digits, and non-_
s).
Whenever you are building a regex dynamically, make sure you
Regex.Escape
method should be used when you need to match some value literally.Thus, use
var s = "v";
var rx1 = new Regex(@"\b" + Regex.Escape(s) + @"\b");
// or
// var rx1 = new Regex(string.Format(@"\b{0}\b", Regex.Escape(s)));
var t = rx1.Replace("The value for v and p are not v and p", "12", 1);
Upvotes: 4