Just wandering, how could I replace a string only when 100% matched in c# .net?For example, I have the following string:
StringBuilder a = new(StringBuilder);
a = "ABC-1 ABC-1.1 ABC-1.1~1"
I'm using the following scrip to replace the string:
a.Replace("ABC-1", "ABC-2");
At the moment the output is like the following :
ABC-2 ABC-2.1 ABC-2.1~1
Instead, I'm looking for the output is like:
ABC-2 ABC-1.1 ABC-1.1~1
Does anyone know how can I do it?
This may help:
var a = "ABC-1 ABC-1.1 ABC-1.1~1";
var result = String.Join(" ", a.Split(' ').Select(x=>x=="ABC-1"? "ABC-2":x));
Result:
"ABC-2 ABC-1.1 ABC-1.1~1"
The "duplicate" being linked to would be a good solution if your input didn't have punctuation in it that signaled the end of a word. So the Regex in that thread doesn't work as-is.
You should be able to use a negative lookahead though.
var a = "ABC-1 ABC-1.1 ABC-1.1~1";
a = Regex.Replace(a, @"\bABC-1\b(?!\S)", "ABC-2");
Console.WriteLine(a); // ABC-2 ABC-1.1 ABC-1.1~1
It basically asserts that the character after the search term is not a non-whitespace character (but also matches if it's the end of the string).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With