Ejemplo n.º 1
0
        private Regex BuildCore(PatternNode pattern, bool exactMatch)
        {
            Visit(pattern);

            if (exactMatch)
            {
                builder.AppendDollar();
            }

            return(RegexFactory.Create(builder.ToString()));
        }
Ejemplo n.º 2
0
        public bool TryCompile(
            string pattern,
            [NotNullWhen(true)] out CompiledPattern?compiledPattern,
            [NotNullWhen(false)] out IReadOnlyList <PatternCompilerError>?errors)
        {
            CheckValue(pattern, nameof(pattern));

            var errorsSink = new PatternCompilerErrorsSink();

            // 1- Resolve the type of the pattern
            var resolvedPattern = resolver.Resolve(pattern);
            var type            = resolvedPattern.Type;

            pattern = resolvedPattern.Pattern;

            Regex         regex;
            ISet <string> variables;

            if (type == PatternType.Regex)
            {
                // 2- Build regex
                regex = RegexFactory.Create(pattern);

                // 3- Get variable names
                var names = regex.GetGroupNames().Where(n => !short.TryParse(n, NumberStyles.None, null, out var _));
                variables = new HashSet <string>(names, StringComparer.OrdinalIgnoreCase);
            }
            else
            {
                // 2- Parse
                if (!parser.TryParse(pattern, errorsSink, out var parsedPattern))
                {
                    compiledPattern = null;
                    errors          = errorsSink.Errors;
                    return(false);
                }

                // 3- Validate
                if (!validator.Validate(parsedPattern, errorsSink))
                {
                    compiledPattern = null;
                    errors          = errorsSink.Errors;
                    return(false);
                }

                // 4- Build regex
                regex = PatternRegexBuilder.Build(parsedPattern, type == PatternType.ExactMatch);

                // 5- Get variable names
                variables = VariableNamesExtractor.Extract(parsedPattern);
            }

            compiledPattern = new CompiledPattern(
                pattern,
                type,
                regex,
                variables);

            errors = null;
            return(true);
        }