Exemple #1
0
        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;
            }
        }