Does anyone know how to use regex to find and replace certain word with
[Keyword]
I tried to use Regex.Replace() but it
You do not need any lambda to re-use the whole match value inside a replacement pattern, you may refer to the whole match value using the $&
backreference. See Substitutions in Regular Expressions:
$&
Includes a copy of the entire match in the replacement string. For more information, see Substituting the Entire Match.
C# code:
var input = "Hello World!";
var keyword = "Hello";
var result = Regex.Replace(input, Regex.Escape(keyword), "<b>$&</b>");
Console.WriteLine(result);
See the online C# demo.
However, this code above makes little sense as you can achieve the same with a mere string .Replace
: var result = input.Replace(keyword, $"<b>{keyword}</b>")
. Hence, here are some ideas where you want to use the regex:
Whole word matching
keyword
consists of letters/digits/underscores ("word" chars) only): Regex.Replace(input, $@"\b{keyword}\b", "<b>$&</b>")
keyword
may contain non-word chars): Regex.Replace(input, $@"(?<!\w){Regex.Escape(keyword)}(?!\w)", "<b>$&</b>")
Regex.Replace(input, $@"(?<!\S){Regex.Escape(keyword)}(?!\S)", "<b>$&</b>")
Case insensitive matching
You may need a regex like this to ensure the same case of the keyword in the replaced string when performing a case insensitive regex search:
Regex.Replace(input, Regex.Escape(keyword), "<b>$&</b>", RegexOptions.IgnoreCase)
See another C# demo:
var keyword = "A+";
Console.WriteLine("Unambiguous WB: " + Regex.Replace("A+B and A++", $@"(?<!\w){Regex.Escape(keyword)}(?!\w)", "<b>$&</b>"));
// => Unambiguous WB: A+B and <b>A+</b>+
keyword = "Hello";
Console.WriteLine("Regular WB: " + Regex.Replace("Hello World! Hello,World!", $@"\b{keyword}\b", "<b>$&</b>"));
// => Regular WB: <b>Hello</b> World! <b>Hello</b>,World!
Console.WriteLine("Whitespace WB: " + Regex.Replace("Hello, Hello Hello!", $@"(?<!\S){Regex.Escape(keyword)}(?!\S)", "<b>$&</b>"));
// => Whitespace WB: Hello, <b>Hello</b> Hello!
keyword = "hello";
Console.WriteLine("Case innsensitive: " + Regex.Replace("Hello, hello World!", Regex.Escape(keyword), "<b>$&</b>", RegexOptions.IgnoreCase));
// => Case innsensitive: <b>Hello</b>, <b>hello</b> World!
You may try this:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string
input = "Hello World!",
keyword = "Hello";
var result = Regex
.Replace(input, keyword, m =>
String.Format("<b>{0}</b>", m.Value));
Console.WriteLine(result);
}
}