简体   繁体   中英

String replace in C# but only the exact character set

I have the following string:

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

and I want to replace 23 with X as below:

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

but when I try it, I get this instead:

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

Is there a way I can get the expecte output?

You will need a regular expression (regexp). The replacement rule here is

  • word boundary
  • 23
  • word boundary

so your code would look like this

 var result = Regex.Replace(input, @"\b23\b", "X");

An alternative approach would be to split your string, replace matching elements and join to new string>

 var result = string.Join(";", input.Split(";").Select(v => v == "23" ? "X" : v));

Update: Update value in Dictionary

Assuming you know the key, that's easy:

 myDict["thekey"] = Regex.Replace(myDict["thekey"], @"\b23\b", "X");

If you want to do this replacement for all items, I'd do it like this, but I'm not sure, if this is the best possible solution:

    [Fact]
    public void Replace_value_in_dict()
    {
        // given
        var mydict = new Dictionary<string, string>
        {
            { "key1", "donothing" },
            { "key2", "23;32;323;34;45" },
        };

        // when
        var result = mydict
            .Select(kv => (kv.Key, Regex.Replace(kv.Value, @"\b23\b", "X")))
            .ToDictionary(x => x.Item1, x => x.Item2);

        // then
        Assert.Equal(result, new Dictionary<string, string>
        {
            { "key1", "donothing" },
            { "key2", "X;32;323;34;45" },
        });
    }

You should use regex

var x="23;32;323;34;45";
var res = Regex.Replace(x,  @"\b23\b", "x");
Console.WriteLine(res);

Working sample

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM