/
Demo.cs
186 lines (168 loc) · 4.84 KB
/
Demo.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// * **********************************************************************************
// * Copyright (c) Clinton Sheppard
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **********************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Scratch.GeneticAlgorithm;
namespace Scratch.RegexFromSamples
{
/// <summary>
/// http://stackoverflow.com/questions/4880402/how-to-auto-generate-regex-from-given-list-of-strings
/// </summary>
[TestFixture]
public class Demo
{
[Test]
public void Given_Sample_A()
{
var target = new[] { "00", "01", "10" };
var dontMatch = new[] { "11" };
GenerateRegex(target, dontMatch, 6);
}
[Test]
public void Should_only_match_alphabetical_once_ignoring_whitespace()
{
var target = new[] { "abc", "abcdefghijk", "abdfkmnpstvxz", "cxy", "cdklstxy",
"bfrtw", "a b c", "acg jko pr", "a z", "v z",
"a b cdefg kl", "uv xyz", "ab de gh", "x yz", "abcdefghijklmnopqrstuvwxyz"};
var dontMatch = new[] { "abbc", "abcb", "a bcdjkrza", "qwerty", "zyxcba",
"abcdfe", "ab c dfe", "a z a", "asdfg", "asd f g", "poqwoieruytjhfg" };
GenerateRegex(target, dontMatch, 30);
}
[Test]
public void Given_Sample_B()
{
var target = new[] { "00", "01", "11" };
var dontMatch = new[] { "10" };
GenerateRegex(target, dontMatch, 4);
}
[Test]
public void Given_Sample_C()
{
var target = new[] { "0", "00", "0000", "00000" };
var dontMatch = new[] { "000", "000000" };
GenerateRegex(target, dontMatch, 9);
}
[Test]
public void Given_Sample_D()
{
// http://stackoverflow.com/questions/15807365/find-simplest-regular-expression-matching-all-given-strings?rq=1
var target = new[] { "h_q1_a", "h_q1_b", "h_q1_c", "h_p2_a", "h_p2_b", "h_p2_c" };
var dontMatch = new string[] { };
GenerateRegex(target, dontMatch, 16);
}
private static void GenerateRegex(IEnumerable<string> target, IEnumerable<string> dontMatch, int expectedLength)
{
string distinctSymbols = new String(target.SelectMany(x => x).Distinct().ToArray());
string genes = distinctSymbols + "?*()[^]+";
Func<string, FitnessResult> calcFitness = str =>
{
if (!IsValidRegex(str))
{
return new FitnessResult
{
Value = Int32.MaxValue
};
}
var regex = new Regex("^" + str + "$");
uint fitness = target.Aggregate<string, uint>(0, (current, t) => current + (regex.IsMatch(t) ? 0U : 1));
uint nonFitness = dontMatch.Aggregate<string, uint>(0, (current, t) => current + (regex.IsMatch(t) ? 10U : 0));
return new FitnessResult
{
Value = fitness + nonFitness
};
};
int targetGeneLength = 1;
for (;;)
{
var best = new GeneticSolver(50 + 10 * targetGeneLength).GetBestGenetically(targetGeneLength, genes, calcFitness);
if (calcFitness(best.GetStringGenes()).Value != 0)
{
Console.WriteLine("-- not solved with regex of length " + targetGeneLength);
targetGeneLength++;
if (targetGeneLength > expectedLength)
{
Assert.Fail("failed to find a solution within the expected length");
}
continue;
}
Console.WriteLine("solved with: " + best);
break;
}
}
private static bool HasBalancedParentheses(string str)
{
int depth = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == ')')
{
depth--;
if (depth < 0)
{
return false;
}
}
if (str[i] == '(')
{
depth++;
}
}
return (depth == 0);
}
private static bool IsValidRegex(string str)
{
if (!HasBalancedParentheses(str))
{
return false;
}
if (str.All(x => "?*+()".Contains(x)))
{
return false;
}
if (")?*+".Any(x => str.First() == x))
{
return false;
}
if (str.Last() == ')')
{
return false;
}
if (str.Contains("()"))
{
return false;
}
if (str.Contains("(*") || str.Contains("(+") || str.Contains("(?"))
{
return false;
}
if (str.Contains("?*") || str.Contains("?+") || str.Contains("??") || str.Contains("*?"))
{
return false;
}
if (str.Contains("++") || str.Contains("**") || str.Contains("+*") || str.Contains("*+"))
{
return false;
}
try
{
new Regex("^" + str + "$");
}
catch (Exception)
{
Console.WriteLine("-- bad: " + str);
return false;
}
return true;
}
}
}