Exemple #1
0
        /// <summary>
        /// Checks to see if a string matches a wildcard pattern
        /// Source: https://stackoverflow.com/questions/271398/what-are-your-favorite-extension-methods-for-c-codeplex-com-extensionoverflow/3527407#3527407
        /// </summary>
        /// <param name="text">The string to check</param>
        /// <param name="pattern">The wildcard pattern</param>
        /// <param name="comparison"></param>
        /// <returns>True if the text matches the pattern, otherwise false</returns>
        public static bool MatchesWildcard(this string text, string pattern,
                                           StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
        {
            if (comparisonType.IsIn(
                    StringComparison.OrdinalIgnoreCase,
                    StringComparison.CurrentCultureIgnoreCase,
                    StringComparison.InvariantCultureIgnoreCase))
            {
                text    = text.ToLower();
                pattern = pattern.ToLower();
            }

            int it = 0;

            while (text.CharAt(it) != 0 && pattern.CharAt(it) != '*')
            {
                if (pattern.CharAt(it) != text.CharAt(it) && pattern.CharAt(it) != '?')
                {
                    return(false);
                }
                it++;
            }

            int cp = 0;
            int mp = 0;
            int ip = it;

            while (text.CharAt(it) != 0)
            {
                if (pattern.CharAt(ip) == '*')
                {
                    if (pattern.CharAt(++ip) == 0)
                    {
                        return(true);
                    }
                    mp = ip;
                    cp = it + 1;
                }
                else if (pattern.CharAt(ip) == text.CharAt(it) || pattern.CharAt(ip) == '?')
                {
                    ip++;
                    it++;
                }
                else
                {
                    ip = mp;
                    it = cp++;
                }
            }

            while (pattern.CharAt(ip) == '*')
            {
                ip++;
            }
            return(pattern.CharAt(ip) == 0);
        }