-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegexPatterns.cs
More file actions
61 lines (51 loc) · 1.77 KB
/
RegexPatterns.cs
File metadata and controls
61 lines (51 loc) · 1.77 KB
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
using System.Text.RegularExpressions;
using System.Text.Json.Serialization;
using System.Text.Json;
namespace csharpClipper;
public static class RegexPatterns
{
private static List<(Regex regex, string replacement)> _patterns;
public static void Initialize()
{
_patterns = [];
try
{
if (!File.Exists("replacements.json"))
{
Logger.Log("replacements.json not found.");
return;
}
var json = File.ReadAllText("replacements.json");
var replacements = JsonSerializer.Deserialize<List<PatternReplacement>>(json) ?? [];
foreach (var pr in replacements)
{
if (!string.IsNullOrWhiteSpace(pr.Pattern))
{
try
{
var regex = new Regex(pr.Pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
_patterns.Add((regex, pr.Replacement));
}
catch (Exception ex)
{
Logger.LogException(ex, $"Invalid regex pattern '{pr.Pattern}'");
}
}
}
Logger.Log($"Loaded {_patterns.Count} regex patterns.");
}
catch (Exception ex)
{
Logger.LogException(ex, "RegexPatterns.Initialize");
_patterns = [];
}
}
public static IEnumerable<(Regex regex, string replacement)> GetPatterns() => _patterns;
}
public class PatternReplacement
{
[JsonPropertyName("pattern")]
public string Pattern { get; set; }
[JsonPropertyName("replacement")]
public string Replacement { get; set; }
}