-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegexDeserializable.cs
68 lines (54 loc) · 2.36 KB
/
RegexDeserializable.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
60
61
62
63
64
65
66
67
68
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Reflection;
namespace AdventOfCode2018
{
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct | AttributeTargets.Field)
]
public class RegexDeserializable : System.Attribute
{
private string regex;
public RegexDeserializable(string regex)
{
this.regex = regex;
}
public static List<T> Deserialize<T>(string serialized)
{
RegexDeserializable[] attributes = (RegexDeserializable[]) typeof(T).GetCustomAttributes(typeof(RegexDeserializable), false);
var regex = attributes[0].regex;
Regex r = new Regex(regex, RegexOptions.Singleline | RegexOptions.Multiline);
List<T> results = new List<T>();
var matches = r.Matches(serialized);
foreach (Match match in matches)
{
var output = Activator.CreateInstance<T>();
foreach (var groupName in r.GetGroupNames().Skip(1))
{
FieldInfo fi = typeof(T).GetField(groupName);
string value = match.Groups[groupName].Value;
var converted = Convert.ChangeType(value, fi.FieldType);
fi.SetValue(output, converted);
}
foreach (var field in typeof(T).GetFields())
{
RegexDeserializable[] fieldAttributes = (RegexDeserializable[])field.GetCustomAttributes(typeof(RegexDeserializable), false);
if (fieldAttributes.Any())
{
var fieldRegex = new Regex(fieldAttributes[0].regex, RegexOptions.Singleline | RegexOptions.Multiline);
foreach (Match fieldMatch in fieldRegex.Matches(match.Groups[0].Value))
{
var converted = Convert.ChangeType(fieldMatch.Groups[1].Value, field.FieldType);
field.SetValue(output, converted);
}
}
}
results.Add(output);
}
return results;
}
}
}