2

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?

Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • What makes something 'complete'? Do you mean 'a word has to have spaces around it (or be at the start or end of the string) - and I want to match the entire word'? If so, use `string.Split`. Iterate over the array and replace entries in the array where they are an exact match (`==`). Then `string.Join` it back together. – mjwills Feb 06 '19 at 04:43

4 Answers4

5

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"
Mehrdad Dowlatabadi
  • 1,335
  • 2
  • 9
  • 11
3

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

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
1

If you want to replace only the first ocurrence, this method can help you:

public static string ReplaceFirst(this string original, string oldValue, string newValue)
{
    var index = original.IndexOf(oldValue);
    if (index >= 0) {
        var prev = original.Substring(0, index);
        var after = original.Substring(index + oldValue.Length);
        return prev + newValue + after;
    }
    return original;
}
Alex LE
  • 20,042
  • 4
  • 30
  • 28
0

To match exact word use regex @"(^|\s)ABC-1.1(\s|$)";

string a = "ABC-1 ABC-1.1 ABC-1.1~1";
    string pattern  = @"(^|\s)ABC-1.1(\s|$)";
    string replace =  Regex.Replace(a, pattern , " test ");

    Console.WriteLine(replace);

output ABC-1 test ABC-1.1~1

Saif
  • 2,611
  • 3
  • 17
  • 37