如果字符串的两端都有其他字符,则C#替换字符串

时间:2019-04-20 08:43:22

标签: c# replace

我想替换一个字符串,如果它是两端的另一个字符串的一部分。

例如,字符串+ 35343 + 3566。我只想在两边都被字符包围的情况下用+0替换+35。因此理想的结果是+35343066。

通常我会使用line.Replace("+35", "0")甚至可能是if-else来满足条件

string a = "+35343+3566";

string b = a.Replace("+35", "0");

我想要'b = +35343066,而不是b = 0343066`

2 个答案:

答案 0 :(得分:2)

您可以为此使用正则表达式。例如:

var replaced = Regex.Replace("+35343+3566", "(?<=.)(\\+35)(?=.)", "0");
// replaced will contain +35343066

这个模式的意思是,+35 (\\+35)必须在(?<=.)之后有一个字符,在(?=.)前必须有一个字符

答案 1 :(得分:1)

您可以使用正则表达式来执行此操作,如下所示:

string a = "+35343+3566";

var regex = new Regex(@"(.)\+35(.)"); // look for "+35" between any 2 characters, while remembering the characters that were found in ${1} and ${2}
string b = regex.Replace(a, "${1}0${2}"); // replace all occurences with "0" surrounded by both characters that were found

请参阅小提琴:https://dotnetfiddle.net/OdCKsy


或更简单一点,如果事实证明只有前缀字符很重要:

string a = "+35343+3566";

var regex = new Regex(@"(.)\+35"); // look for a character followed by "+35", while remembering the character that was found in ${1}
string b = regex.Replace(a, "${1}0"); // replace all occurences with the character that was found followed by a 0

请参阅小提琴:https://dotnetfiddle.net/9jEHMN