开发者

how to replace some character b/w strings in c#?

开发者 https://www.devze.com 2023-02-21 18:24 出处:网络
how to replace some character b/w strings in c#? suppose string is :1-开发者_JAVA技巧2-5-7-8-9-10-15

how to replace some character b/w strings in c#?

suppose

string is : 1-开发者_JAVA技巧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?


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.


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'.


You will need to replace -5- with -2-


Try this

yourString = yourString.Replace("-5-","-2-");


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


Do you have a separator?

E.g. If you really have the string link 1-2-5... you can replace '-5' with -2.

0

精彩评论

暂无评论...
验证码 换一张
取 消