Highlight a list of words using a regular expression in c#

前端 未结 5 1223
鱼传尺愫
鱼传尺愫 2021-01-13 15:56

I have some site content that contains abbreviations. I have a list of recognised abbreviations for the site, along with their explanations. I want to create a regular expre

5条回答
  •  无人及你
    2021-01-13 16:36

    I'm doing pretty exactly what you're looking for in my application and this works for me: the parameter str is your content:

    public static string GetGlossaryString(string str)
            {
                List glossaryWords = GetGlossaryItems();//this collection would contain your abbreviations; you could just make it a Dictionary so you can have the abbreviation-full term pairs and use them in the loop below 
    
                str = string.Format(" {0} ", str);//quick and dirty way to also search the first and last word in the content.
    
                foreach (string word in glossaryWords)
                    str = Regex.Replace(str, "([\\W])(" + word + ")([\\W])", "$1$2$3", RegexOptions.IgnoreCase);
    
                return str.Trim();
            }
    

提交回复
热议问题