-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlphaNumericStringComparer.cs
More file actions
76 lines (59 loc) · 2.23 KB
/
AlphaNumericStringComparer.cs
File metadata and controls
76 lines (59 loc) · 2.23 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace nl.mijnaansluiting.sorting
{
public class AlphaNumericStringComparer : IComparer<string>
{
#region Private Fields
private static readonly Regex regex = new Regex(@"((?<intnegative>[\-\+\$][\d]+)|(?<int>[\d]+)|(?<stringlower>[a-z]+)|(?<stringupper>[A-Z]+)|(?<special>[\s]+))", RegexOptions.Singleline);
private readonly int paddingTotalWidth;
public AlphaNumericStringComparer(int paddingTotalWidth = 16)
{
this.paddingTotalWidth = paddingTotalWidth;
}
#endregion Private Fields
#region Private Methods
private static string FindGroupName(Match match)
{
return match.Groups
.Cast<Group>()
.Where((group, index) => group.Success && !group.Name.Equals($"{index}"))
.Select(x => x.Name)
.FirstOrDefault();
}
private string MatchEvaluator(Match match)
{
switch (FindGroupName(match))
{
case "intnegative":
var value1 = $"{match.Value.Replace("-", string.Empty)}0".PadLeft(paddingTotalWidth, '0');
return value1;
case "int":
var value2 = $"{match.Value}1".PadLeft(paddingTotalWidth, '0');
return value2;
case "stringlower":
return $"a{match.Value}";
case "stringupper":
return $"A{match.Value}";
case "special":
return $"?{match.Value}";
default:
return $"/{match.Value}";
}
}
private string Parse(string value)
{
value = value.Trim().Replace(" ", string.Empty);
return regex.Replace(value, MatchEvaluator);
}
#endregion Private Methods
#region Public Methods
public int Compare(string left, string right)
{
int result = Parse(left).CompareTo(Parse(right));
return result == 0 ? right.CompareTo(left) : result;
}
#endregion Public Methods
}
}