How to search and replace exact matching strings only
//Find and Replace A word in c#
public static class Program
{
public static string Replace(this String str, char[] chars, string replacement)
{
StringBuilder output = new StringBuilder(str.Length);
bool replace = false;
if (chars.Length - 1 < 1)
{
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
replace = false;
// int val = Regex.Matches(ch.ToString(), @"[a-zA-Z]").Count;
for (int j = 0; j < chars.Length; j++)
{
if (chars[j] == c)
{
replace = true;
break;
}
}
if (replace)
output.Append(replacement);
else
output.Append(c);
}
}
else
{
int j = 0;
int truecount = 0;
char c1 = '\0';
for (int k = 0; k < str.Length; k++)
{
c1 = str[k];
if (chars[j] == c1)
{
replace = true;
truecount ++;
}
else
{
truecount = 0;
replace = false;
j = 0;
}
if(truecount>0)
{
j++;
}
if (j > chars.Length-1)
{
j = 0;
}
if (truecount == chars.Length)
{
output.Remove(output.Length - chars.Length+1, chars.Length-1);
// output.Remove(4, 2);
if (replace)
output.Append(replacement);
else
output.Append(c1);
}
else
{
output.Append(c1);
}
}
}
return output.ToString();
}
static void Main(string[] args)
{
Console.WriteLine("Enter a word");
string word = (Console.ReadLine());
Console.WriteLine("Enter a word to find");
string find = (Console.ReadLine());
Console.WriteLine("Enter a word to Replace");
string Rep = (Console.ReadLine());
Console.WriteLine(Replace(word, find.ToCharArray(), Rep));
Console.ReadLine();
}
}
string pattern = @"\bAdd\b";
string input = "Add Additional String to text box";
string result = Regex.Replace(input, pattern, "Insert", RegexOptions.None);
"\bAdd\b" ensures that it will match the "Add" which is not part of other words. Hope it's helpful.
answer for:
"This solution doesnt work if I need to replace a word that starts with @. Fiddle here dotnetfiddle.net/9kgW4h How can I get this working in this scenario. – Frenz Jan 16 '17 at 5:46"
possible solution:
public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord) {
string searchString = find.StartsWith("@") ? $@"@\b{find.Substring(1)}\b" : $@"\b{find}\b";
string textToFind = matchWholeWord ? searchString : find;
return Regex.Replace(input, textToFind, replace);
}
You can use Regex to do this:
Extension method example:
public static class StringExtensions
{
public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find;
return Regex.Replace(input, textToFind, replace);
}
}
Usage:
string text = "Add Additional String to text box";
string result = text.SafeReplace("Add", "Insert", true);
result: "Insert Additional String to text box"