string input = @"COUNTER = $40
CLOCK_COUNTER = $60";
string name = Regex.Replace(input, @"\bCOUNTER\b", "COUNT");
\b
отмечает границы слов.
Единственной альтернативой Regex является разработка собственного алгоритма! Найдите слово «СЧЕТЧИК» и проверьте, не является ли предыдущий и следующий символ символом слова.
EDIT
Вот мое решение в качестве метода расширения:
public static class ReplaceWordNoRegex
{
private static bool IsWordChar(char c)
{
return Char.IsLetterOrDigit(c) || c == '_';
}
public static string ReplaceFullWords(this string s, string oldWord, string newWord)
{
if (s == null) {
return null;
}
int startIndex = 0;
while (true) {
int position = s.IndexOf(oldWord, startIndex);
if (position == -1) {
return s;
}
int indexAfter = position + oldWord.Length;
if ((position == 0 || !IsWordChar(s[position - 1])) && (indexAfter == s.Length || !IsWordChar(s[indexAfter]))) {
s = s.Substring(0, position) + newWord + s.Substring(indexAfter);
startIndex = position + newWord.Length;
} else {
startIndex = position + oldWord.Length;
}
}
}
}
РЕДАКТИРОВАНИЕ № 2:
И вот решение с помощью StringBuilder.
public static string ReplaceFullWords(this string s, string oldWord, string newWord)
{
if (s == null) {
return null;
}
int startIndex = 0; // Where we start to search in s.
int copyPos = 0; // Where we start to copy from s to sb.
var sb = new StringBuilder();
while (true) {
int position = s.IndexOf(oldWord, startIndex);
if (position == -1) {
if (copyPos == 0) {
return s;
}
if (s.Length > copyPos) { // Copy last chunk.
sb.Append(s.Substring(copyPos, s.Length - copyPos));
}
return sb.ToString();
}
int indexAfter = position + oldWord.Length;
if ((position == 0 || !IsWordChar(s[position - 1])) && (indexAfter == s.Length || !IsWordChar(s[indexAfter]))) {
sb.Append(s.Substring(copyPos, position - copyPos)).Append(newWord);
copyPos = position + oldWord.Length;
}
startIndex = position + oldWord.Length;
}
}