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

前端 未结 5 1220
鱼传尺愫
鱼传尺愫 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:35

    First you would need to Regex.Escape() all the input strings.

    Then you can look for them in the string, and iteratively replace them by the markup you have in mind:

    string abbr      = "memb";
    string word      = "Member";
    string pattern   = String.Format("\b{0}\b", Regex.Escape(abbr));
    string substitue = String.Format("[a title=\"{0}\"]{1}[/a]", word, abbr);
    string output    = Regex.Replace(input, pattern, substitue);
    

    EDIT: I asked if a simple String.Replace() wouldn't be enough - but I can see why regex is desirable: you can use it to enforce "whole word" replacements only by making a pattern that uses word boundary anchors.

    You can go as far as building a single pattern from all your escaped input strings, like this:

    \b(?:{abbr_1}|{abbr_2}|{abbr_3}|{abbr_n})\b
    

    and then using a match evaluator to find the right replacement. This way you can avoid iterating the input string more than once.

提交回复
热议问题