Replace multiple Regex Matches each with a different replacement

后端 未结 1 952
时光取名叫无心
时光取名叫无心 2020-12-11 04:06

I have a string that may or may not have multiple matches for a designated pattern.

Each needs to be replaced.

I have this code:

var pattern          


        
相关标签:
1条回答
  • 2020-12-11 04:41

    Use a Match evaluator inside the Regex.Replace:

    var pattern = @"\$\$\@[a-zA-Z0-9_]*\b";
    var stringVariableMatches = Regex.Replace(strValue, pattern, 
            m => variablesDictionary[m.Value]);
    

    The Regex.Replace method will perform global replacements, i.e. will search for all non-overlapping substrings that match the indicated pattern, and will replace each found match value with the variablesDictionary[m.Value].

    Note that it might be a good idea to check if the key exists in the dictionary.

    See a C# demo:

    using System;
    using System.IO;
    using System.Text.RegularExpressions;
    using System.Collections.Generic;
    using System.Linq;
    public class Test
    {
        public static void Main()
        {
            var variablesDictionary = new Dictionary<string, string>();
            variablesDictionary.Add("$$@Key", "Value");
            var pattern = @"\$\$@[a-zA-Z0-9_]+\b";
            var stringVariableMatches = Regex.Replace("$$@Unknown and $$@Key", pattern, 
                    m => variablesDictionary.ContainsKey(m.Value) ? variablesDictionary[m.Value] : m.Value);
            Console.WriteLine(stringVariableMatches);
        }
    }
    

    Output: $$@Unknown and Value.

    0 讨论(0)
提交回复
热议问题