Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search and replace exact matching strings only

Tags:

c#

I need to search in a string and replace a certain string

Ex: Search String "Add Additional String to text box". Replace "Add" with "Insert"

Output expected = "Insert Additional String to text box"

If you use string s="Add Additional String to text box".replace("Add","Insert");

Output result = "Insert Insertitional String to text box"

Have anyone got ideas to get this working to give the expected output?

Thank you!

like image 418
Darshana Avatar asked Dec 14 '12 00:12

Darshana


People also ask

How do you exactly match a string in Python?

Exact match (equality comparison): == , != As with numbers, the == operator determines if two strings are equal. If they are equal, True is returned; if they are not, False is returned. It is case-sensitive, and the same applies to comparisons by other operators and methods.

How do you find and replace a word in a string in C#?

In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.


2 Answers

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"

like image 73
sa_ddam213 Avatar answered Sep 18 '22 15:09

sa_ddam213


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.

like image 21
Xiaodan Mao Avatar answered Sep 20 '22 15:09

Xiaodan Mao