Exemplo n.º 1
0
        public string Replace(string text, string pattern, Func<PatternMatch, string> replacement)
        {
            try
            {
                var cached = _cache.Get(
                    "Onestop.Patterns:" + pattern,
                    ctx => new Tuple<IEnumerable<string>, Regex>(GetGroups(pattern), Convert(pattern)));

                return cached.Item2.Replace(text, match =>
                {
                    var details = new PatternMatch
                    {
                        Groups = cached.Item1.Select(g => new KeyValuePair<string, string>(g, match.Groups[g].Value)),
                        BaseExpression = cached.Item2,
                        IsMatch = match.Success
                    };

                    return replacement(details);
                });
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error when trying to replace pattern {0}", pattern);
                return text;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Matches a given text against a given wildcard pattern.
        /// </summary>
        /// <param name="text">Text to match.</param>
        /// <param name="pattern">Pattern to match against.</param>
        /// <param name="details">Object containing detailed match information.</param>
        /// <returns>True if match is found or false otherwise.</returns>
        public bool TryMatch(string text, string pattern, out PatternMatch details)
        {
            try
            {
                pattern = "{^}" + pattern + "{$}";
                var cached = _cache.Get(
                    "Onestop.Patterns:" + pattern,
                    ctx => new Tuple<IEnumerable<string>, Regex>(GetGroups(pattern), Convert(pattern)));

                var match = cached.Item2.Match(text);
                details = new PatternMatch
                {
                    Groups = cached.Item1.Select(g => new KeyValuePair<string, string>(g, match.Groups[g].Value)),
                    BaseExpression = cached.Item2,
                    IsMatch = match.Success
                };

                return details.IsMatch;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Error when trying to match pattern {0}", pattern);
                details = null;
                return false;
            }
        }