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

问题描述 投票:-2回答:2

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

比如说一个字符串+ 35343 + 3566。我想将+35替换为0,只要它被两边的字符包围。所以期望的结果将是+35343066。

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

string a = "+35343+3566";

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

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

c# replace
2个回答
2
投票

你可以使用正则表达式。例如:

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

所以这种模式说的是+35 (\\+35)必须在(?<=.)后面有一个角色,在(?=.)前面有一个角色


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

© www.soinside.com 2019 - 2024. All rights reserved.