Created
August 21, 2019 14:44
-
-
Save Himura2la/26bd0ed72e01f235eedb5f2735862449 to your computer and use it in GitHub Desktop.
Replaces matches using string.Remove().Insert()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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