C# 中的字符串替换,但只有确切的字符集

我有以下字符串:

string x = "23;32;323;34;45";

我想用 X 替换 23 ,如下所示:

x = "x:32;323;34;45";

但是当我尝试它时,我得到了这个:

x = "x:32;3x;34;45";

有没有办法获得预期的输出?


千巷猫影
浏览 112回答 2
2回答

慕桂英4014372

您将需要一个正则表达式 (regexp)。这里的替换规则是词界23词界所以你的代码看起来像这样&nbsp;var&nbsp;result&nbsp;=&nbsp;Regex.Replace(input,&nbsp;@"\b23\b",&nbsp;"X");另一种方法是拆分字符串,替换匹配元素并加入新字符串>&nbsp;var&nbsp;result&nbsp;=&nbsp;string.Join(";",&nbsp;input.Split(";").Select(v&nbsp;=>&nbsp;v&nbsp;==&nbsp;"23"&nbsp;?&nbsp;"X"&nbsp;:&nbsp;v));更新:更新字典中的值假设您知道密钥,这很容易:&nbsp;myDict["thekey"]&nbsp;=&nbsp;Regex.Replace(myDict["thekey"],&nbsp;@"\b23\b",&nbsp;"X");如果您想对所有项目进行此替换,我会这样做,但我不确定这是否是最好的解决方案:&nbsp; &nbsp; [Fact]&nbsp; &nbsp; public void Replace_value_in_dict()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // given&nbsp; &nbsp; &nbsp; &nbsp; var mydict = new Dictionary<string, string>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "key1", "donothing" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "key2", "23;32;323;34;45" },&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; // when&nbsp; &nbsp; &nbsp; &nbsp; var result = mydict&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(kv => (kv.Key, Regex.Replace(kv.Value, @"\b23\b", "X")))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToDictionary(x => x.Item1, x => x.Item2);&nbsp; &nbsp; &nbsp; &nbsp; // then&nbsp; &nbsp; &nbsp; &nbsp; Assert.Equal(result, new Dictionary<string, string>&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "key1", "donothing" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { "key2", "X;32;323;34;45" },&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }

守候你守候我

你应该使用正则表达式var x="23;32;323;34;45";var res = Regex.Replace(x,&nbsp; @"\b23\b", "x");Console.WriteLine(res);
打开App,查看更多内容
随时随地看视频慕课网APP