Home > Blockchain >  How to do a string replace on a number that is on its own and not part of a string or another number
How to do a string replace on a number that is on its own and not part of a string or another number

Time:10-29

I have a string: string MyString = value1, 111; _1 1.00 H1 1

If I do MyString = MyString.Replace("1", "2") it will replace every "1" with a "2". I only want to replace a 1 with a 2 when it is on its own, not when it is part of something else (in this case it's the last one).

Is there like a string replace method that would check if the target char is on its own?

That means the target char is either: A) The first char of the string and followed by a space. B) The last char of the string followed after a space. C) In the middle of the string and is between two spaces.

The expected result in this case would be MyString = value1, 111; _1 1.00 H1 2. But I'm looking for the method to work no matter where in the string the target char is.

CodePudding user response:

This is a classic job for regular expressions. One simple way would be like this:

Regex.Replace("value1, 111; _1 1.00 H1 1",   @"(?<=^|\s)(1)(?=$|\s)", "2");
Regex.Replace("value1, 111; 1 1.00 H1 1",    @"(?<=^|\s)(1)(?=$|\s)", "2");
Regex.Replace("1 value1, 111; _1 1.00 H1 1", @"(?<=^|\s)(1)(?=$|\s)", "2");

Depending on your needs, you'll probably want to improve this further - e.g. if you're applying this on a lot of input values, you'll want to have the Regex precompiled.

Make sure that the value to be replaced (1 here) is properly escaped, especially if you want to use it for something other than just simple numbers. You can further tweak the expression to decide what exactly counts as breaks. In this example, I've used start/end of string (^ and $ respectively) and any whitespace (\s).

?<= and ?= are lookaheads - essentially parts that need to match, but aren't returned in the actual match result. This means that we're only replacing the part between them (1).

  • Related