Learning
Learning

Reputation: 20001

Regex Replaces the text with users case text, how to maintain the actual word case

I am matching and replacing matching words with <span>keyword</span>,

Support users enter the search keyword in lower case as united states it matches the keyword and replaces it

Actual String

String str = "This is United States Of America"

After Match & Replace function string is replaced with lower case match string as entered by the user

This is united states Of America after match

I want to match and replace the string while maintaining the actual case of the matched word or words in the string or database

I use following code for this. How can i alter this so that my requirements are meant

    string pattern = @"(\b(?:" + Request["SearchKeyword"].ToString().Trim() + @")\b))";
    regex = new Regex(pattern, RegexOptions.IgnoreCase);
    result = regex.Replace(result, "<span class='highlight'>" + Request["SearchKeyword"].ToString() + "</span>",);

Desired Output expected This is United States Of America

Upvotes: 0

Views: 64

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626844

You need to use the Match().Value instead of the original request string.

Here is the code you can use:

var req = "united states";
var str = "This is United States Of America";
var pattern = @"((?<=^\p{P}*|\p{Zs})(?:" + req.ToString().Trim() + @")(?=\p{P}*$|\p{Zs}))";
var regx = new Regex(pattern, RegexOptions.IgnoreCase);
var m = regx.Match(str);
var result = string.Empty;
if (m.Success)
   result = regx.Replace(str, "<span class='highlight'>" + m.Value + "</span>");

Output:

enter image description here

EDIT: (just in case)

Using a lambda, you can obtain the same result:

var regx = new Regex(pattern, RegexOptions.IgnoreCase);
var result = regx.Replace(str, m => "<span class='highlight'>" + m.Value + "</span>");

It is safe even in case we have no match.

Upvotes: 1

ASh
ASh

Reputation: 35680

you can use another overload of Regex.Replace method with MatchEvaluator

string str = "This is United States Of America";
string SearchKeyword = "united states";
string pattern = @"(\b(?:" + SearchKeyword.Trim() + @")\b)";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
var result = regex.Replace(str, new MatchEvaluator(m => "<span class='highlight'>" + m.ToString() + "</span>"));

Upvotes: 1

Related Questions