Reputation: 755
how to replace some character b/w strings in c#?
suppose
string is : 1-2-5-7-8-9-10-15
i use replace function
when i replace 5
with 2
it also replace the last 15
to 12
because of 5
there.
so how can i get the right output?
Upvotes: 3
Views: 319
Reputation: 38590
new Regex(@"\b5\b").Replace("1-2-5-7-8-9-10-15", "2");
The \b
matches a word boundary. This means that '-5-' will be matched but '-15-' won't.
It will will also handle the case where the match is at the edge of the string and does not have a hyphen on both sides, e.g. '5-' and '-5'.
Upvotes: 4
Reputation: 174299
You can use this:
yourString.Split("-").Select(s => Regex.Replace(s, "^5$", "2")).Aggregate((a,b) => a + "-" + b);
In contrast to most of the other answers here, this also handles the case, when the string to be replaced is at the beginning or the end of the input string.
Upvotes: 7
Reputation: 3596
you could use a regex replace and replace with a regex something like
[^\d]*5[^\d]*
to match a 5 without any numbers next to it
Upvotes: 2
Reputation: 8920
Do you have a separator?
E.g. If you really have the string link 1-2-5... you can replace '-5' with -2.
Upvotes: 0