Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace text with RegEx (ignoring case) but keep case

Status
Not open for further replies.

ralphtrent

Programmer
Jun 2, 2003
958
US
Hello
I am using RegEx to search for text in a string. Since I need the search to be case-insentive this looked to be my only option. My main purpose for the replacement is to highlight the backround of a text (based on a search). This works well, but the text gets replaced with the incorrect case. Here is my code

Code:
string sWorkNotes = "Ralph and Pete work together"
string[] sSearchPhrase = new string[2]{"ralph","pete"};
foreach(string s in sSearchPhrase)
{
	sWorkNotes = System.Text.RegularExpressions.Regex.Replace(sWorkNotes, s, "<span style='background-color:yellow;'>" + s + "</span>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
}

this is the output
Code:
[highlight]ralph[/highlight] and [highlight]pete[/highlight] work together

what I need is this
Code:
[highlight]Ralph[/highlight] and [highlight]Pete[/highlight] work together

I need to keep the same case as the origional string. The reason it is getting lower cased is because the text is lower cased in my array.

Code:
string[] sSearchPhrase = new string[2]{"ralph","pete"};

Any ideas on how i can do this?
 
I got this working. Here is my code:

Code:
//Calling Code
.
.
.
sDescription = lblDescription.Text;
sDescription.Text = HighlightText(sDescription,"My Search Phrase");
lblDescription.Text = sDescription
.
.
.

private string HighlighText(string Source, string SearchText)
{
	return Regex.Replace(Source,SearchText,new MatchEvaluator(ReplaceKeyWords), RegexOptions.IgnoreCase);
}

public string ReplaceKeyWords(Match m) 
{
	return "<span style='background-color:yellow;'>" + m.Value + "</span>"; 
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top