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

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

    Not sure how well this will scale to a big word list, but I think it should give the output you want (although in your question the 'result' seems identical to 'content')?

    Anyway, let me know if this is what you're after

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var input = @"This is just a little test of the memb to see if it gets picked up. 
    Deb of course should also be caught here.";
                var dictionary = new Dictionary
                {
                    {"memb", "Member"}
                    ,{"deb","Debut"}
                };
                var regex = "(" + String.Join(")|(", dictionary.Keys.ToArray()) + ")";
                foreach (Match metamatch in Regex.Matches(input
                   , regex  /*@"(memb)|(deb)"*/
                   , RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture))
                { 
                    input = input.Replace(metamatch.Value, dictionary[metamatch.Value.ToLower()]);
                }
                Console.Write (input);
                Console.ReadLine();
            }
        }
    }
    

提交回复
热议问题