Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string only when 100% matched [duplicate]

Tags:

c#

.net

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?

like image 342
Jin Yong Avatar asked Sep 13 '26 00:09

Jin Yong


2 Answers

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"
like image 105
Mehrdad Dowlatabadi Avatar answered Sep 15 '26 12:09

Mehrdad Dowlatabadi


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).

like image 27
Grant Winney Avatar answered Sep 15 '26 12:09

Grant Winney