Replace multiple Regex Matches each with a different replacement

Mortalus

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 = @"\$\$\@[a-zA-Z0-9_]*\b";
var stringVariableMatches = Regex.Matches(strValue, pattern);
var sb = new StringBuilder(strValue);

foreach (Match stringVarMatch in stringVariableMatches)
{
    var stringReplacment = variablesDictionary[stringVarMatch.Value];
    sb.Remove(stringVarMatch.Index, stringVarMatch.Length)
            .Insert(stringVarMatch.Index, stringReplacment);
}

return sb.ToString();

The problem is that when I have several matches the first is replaced and the starting index of the other is changed so that in some cases after the replacement when the string is shorten I get an index out of bounds..

I know I could just use Regex.Replace for each match but this sound performance heavy and wanted to see if someone could point a different solution to substitute multiple matches each with a different string.

Wiktor Stribiżew

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Regex replacement in Javascript with multiple matches

From Dev

notepad++ regex to replace multiple values with different replacement

From Dev

Using regex in Find/Replace to replace multiple matches

From Dev

C# Regex.Replace - search for matches in replacement string as well

From Dev

Multiple preg_replace RegEx for different URLs

From Dev

Regex multiple pattern replacement

From Dev

Regex multiple pattern replacement

From Dev

Regex replacement is not being performed on all matches

From Dev

Regex Replacement with Repetition, How do I replace each "\r\n" in X number of occurrences of ".+?\r\n"?

From Dev

multiple regex matches in a string

From Dev

multiple matches REGEX

From Dev

Multiple matches with regex

From Dev

Regex to matches multiple string

From Dev

bash regex multiple matches

From Dev

Regex multiple matches in a search

From Dev

gsub: replace regex match with regex replacement string

From Dev

Python Regex - search and replace matches

From Dev

Regex URL - replace matches by links

From Dev

Overlapping regex matches with replace method

From Dev

Multiple replacement with just one regex

From Dev

Notepad regex replacement : how to split and replace a result?

From Dev

JavaScript, Regex - `.replace` is only removing the last-matched part (when multiple matches)

From Dev

Replace a set of pattern matches with corresponding replacement strings in R

From Dev

perl regex: multiple matches as variables

From Dev

Regex: text before multiple matches

From Dev

Regex to fail if multiple matches found

From Dev

regex multiple matches with OR look behind

From Dev

Regex Match Collection multiple matches

From Dev

Regex multiple matches for HTML attributes

Related Related

HotTag

Archive