Skip to content

Instantly share code, notes, and snippets.

@Himura2la
Created August 21, 2019 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Himura2la/26bd0ed72e01f235eedb5f2735862449 to your computer and use it in GitHub Desktop.
Save Himura2la/26bd0ed72e01f235eedb5f2735862449 to your computer and use it in GitHub Desktop.
Replaces matches using string.Remove().Insert()
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace LowLevelReplace {
class Program {
static readonly Regex template = new Regex(@"({(.*?)})", RegexOptions.Compiled);
static readonly Dictionary<string, string> values = new Dictionary<string, string>() {
{ "meow", "nya" },
{ "cute", "kawaii" }
};
class MatchesReverser : IComparer {
public int Compare(object x, object y) => (y as Match).Index - (x as Match).Index;
}
static string ReplaceAll(string text) {
var matches = new ArrayList(template.Matches(text));
matches.Sort(new MatchesReverser()); // Replacing from end to beginning for not to mess
foreach(Match match in matches) { // with indices while changing the original string
text = text.Remove(match.Groups[1].Index, match.Groups[1].Length)
.Insert(match.Groups[1].Index, GetValue(match.Groups[2].Value));
}
return text;
}
static string GetValue(string key) {
if(values.ContainsKey(key)) {
return values[key];
}
return "[Unresolved]";
}
static void Main(string[] args) {
Console.WriteLine(ReplaceAll("{cute} creatures say meow {meow} meow"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment