C # use regular expressions to Replace case-insensitive strings -- custom highlighting in C # is difficult to Replace strings that are case-insensitive, even if it takes a lot of effort to do it, the efficiency is still very low, the correct method should be to use regular expressions. To use a regular expression, you must first reference the namespace:
Using System. Text. RegularExpressions; |
Then, it is very simple to use:
Regex. Replace (string, substring to be replaced, Replace the substring character, RegexOptions. IgnoreCase) |
The final parameter RegexOptions. ignoreCase indicates that case sensitivity is ignored. However, I want to highlight all matched substrings in a group of strings (that is, make the font style different from other parts of the string ), the following statement inserts an html tag at both ends of the string to highlight the string, but the highlighted string is the search string for the substring. The case is different from the original one. For example, the keyString I searched in "13th Asp.net implementations" is "asp ", the replaced string becomes "13th <span class =" Highlight "> asp </span>. net implementation, rather than the expected "13th <span class =" Highlight "> Asp </span>. net implementation"
DocumentResume [I] = Regex. replace (hitDoc. get ("resume"), keyString, "<span class = \" Highlight \ ">" + keyString + "</span>", RegexOptions. ignoreCase ); |
Therefore, Replace directly using a regular expression cannot meet my needs. Instead, we need to use the Match search method of the regular expression (Match searches for a single entry and multiple Matchs entries ), insert the html tag before and after the matched substring. For details, refer to the following code:
String pain = hitDoc. Get ("resume"); // string System. Text. RegularExpressions. MatchCollection m = Regex. Matches (pain, keyString, RegexOptions. IgnoreCase); // ignore keywords in case-insensitive search strings For (int j = 0; j <m. Count; j ++) // Insert the loop before and after the matched substring { // J × 31 adds the length of the pain string to insert html tags: Pain = pain. Insert (m [j]. Index + keyString. Length + j * 31), "</span>"); // Insert the html Tag after the keyword Pain = pain. Insert (m [j]. Index + j * 31), "<span class = \" Highlight \ ">"); // Insert html tags before keywords } |
Of course, html tags do not work if they are inserted randomly. Add the following custom style to the header area of the page code for displaying the inserted string.
<STYLE type = text/css> <! --. Highlight { Color: #00 FFFF; Font-style: italic; Font-size: larger; } --> </STYLE> |