C#: Extension method to append specific character at start of each matching word in string

Standard
using System.Text.RegularExpressions;

public static string ReplaceKeywordsWithHashtags(this string data, params string[] filterTerms)
        {
            foreach (string term in filterTerms)
            {
                var item = term.Trim();
                if (!string.IsNullOrEmpty(item))
                {
                    if (data.ToLower().Contains(item))
                        data = Regex.Replace(data, item, '#' + item, RegexOptions.IgnoreCase);
                }
            }
            return data;
        }

Usage:

string temp = "Hello World! Hello World! Hello World! Hello World!";
string[] filter = {"abc", "xyz", "hello"};
string result = temp.ReplaceKeywordsWithHashtags(filter);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s