-
Notifications
You must be signed in to change notification settings - Fork 0
/
StringFormatter.cs
59 lines (50 loc) · 1.65 KB
/
StringFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace SuperPerformanceChart
{
public class StringFormatter
{
private readonly IFormatProvider _formatProvider;
private readonly string _mask;
private Dictionary<string, ParameterInfo> Parameters { get; set; }
public StringFormatter(string mask, IFormatProvider formatProvider = null)
{
Parameters = new Dictionary<string, ParameterInfo>();
var regex = new Regex(@"@(\w+)?");
var matches = regex.Matches(mask);
foreach (Match match in matches)
{
Parameters.Add(match.Groups[0].Value, new ParameterInfo() { FullMatch = match.Groups[0].Value, Value = null });
}
_formatProvider = formatProvider;
_mask = mask;
}
public bool HasParameter(string key)
{
return Parameters.ContainsKey(key);
}
public bool Set(string key, object val)
{
if (Parameters.ContainsKey(key))
{
Parameters[key].Value = val;
return true;
}
else
{
return false;
}
}
public override string ToString()
{
return Parameters.Aggregate(_mask, (current, parameter) => current.Replace(parameter.Value.FullMatch, parameter.Value.Value?.ToString()));
}
private class ParameterInfo
{
public object Value { get; internal set; }
public string FullMatch { get; internal set; }
}
}
}