So I'm trying to write a way to replace "100¢" to "100 cents" using Regex. The pattern I'm using is (\d+)(¢). On top of that, I'm also trying to replace other things, so I would need a Dictionary data structure to hold all these regex patterns as keys, and the values I'd want to replace them with as the dictionary value.
The code I have so far is this:
var replacementsMap = new Dictionary<string, string>()
{
{@"(\d+)(¢)", "$1 cents"}
};
There would be more in the dictionary, but to keep it simple, I'll just add that one pattern-value pair. I'm using back references to have the first capturing group with "cents" after it rather than the symbol.
Ex: 5¢ -> 5 cents
To replace, I'm doing it like this:
string input = "100¢";
Console.WriteLine(input); //showing original input
var regex = new Regex(String.Join("|",replacementsMap.Keys));
var newStr = regex.Replace(input, m => replacementsMap[m.Value]);
Console.WriteLine(newStr); //showing new input
The error I'm getting is this, and I'm not really sure where I'm going wrong with my implementation:
Unhandled exception. System.Collections.Generic.KeyNotFoundException: The given key '100¢' was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Program.<>c__DisplayClass1_0.<Main>b__0(Match m) in Program.cs:line 79
at System.Text.RegularExpressions.Regex.<>c.<Replace>b__99_0(ValueTuple`5& state, Match match)
at System.Text.RegularExpressions.Regex.RunAllMatchesWithCallback[TState](String inputString, ReadOnlySpan`1 inputSpan, Int32 startat, TState& state, MatchCallback`1 callback, RegexRunnerMode mode, Boolean reuseMatchObject)
at System.Text.RegularExpressions.Regex.RunAllMatchesWithCallback[TState](String input, Int32 startat, TState& state, MatchCallback`1 callback, RegexRunnerMode mode, Boolean reuseMatchObject)
at System.Text.RegularExpressions.Regex.Replace(MatchEvaluator evaluator, Regex regex, String input, Int32 count, Int32 startat)
at System.Text.RegularExpressions.Regex.Replace(String input, MatchEvaluator evaluator)
at Program.Main() in Program.cs:line 79