Determine if a string includes a pattern using "*" and "?" as wild cards - CSharp System

CSharp examples for System:String Match

Description

Determine if a string includes a pattern using "*" and "?" as wild cards

Demo Code


using System.Collections;
using System.Text;
using System;/*from w w  w. j  a va  2  s .  c  o  m*/

public class Main{
        /// <summary>
        /// Determine if a string includes a pattern using "*" and "?" as wild cards 
        /// </summary>
        /// <param name="source"></param>
        /// <param name="pattern"></param>
        /// <param name="caseSensitive"></param>
        /// <returns>True if pattern wild card matches</returns>
        public static bool MatchWildCard(string source, string pattern, bool caseSensitive)
        {
            if (!caseSensitive)
            {
                pattern = pattern.ToLower();
                source = source.ToLower();
            }

            int nText = 0;
            int nPattern = 0;
            //const char *cp = NULL, *mp = NULL;
            int mp = 0;
            int cp = 0;

            while (nText < source.Length && nPattern < pattern.Length && (pattern[nPattern] != '*'))
            {
                if ((pattern[nPattern] != source[nText]) && (pattern[nPattern] != '?'))
                {
                    return false;
                }
                nPattern++;
                nText++;
            }

            while (nText < source.Length)
            {
                if (pattern[nPattern] == '*')
                {
                    nPattern++;
                    if (nPattern >= pattern.Length)
                    {
                        return true;
                    }
                    mp = nPattern;
                    cp = nText + 1;
                }
                else if ((pattern[nPattern] == source[nText]) || (pattern[nPattern] == '?'))
                {
                    nPattern++;
                    nText++;
                }
                else
                {
                    nPattern = mp;
                    nText = cp++;
                }
            }

            while (nPattern < pattern.Length && pattern[nPattern] == '*')
            {
                nPattern++;
            }
            return nPattern >= pattern.Length;
        }
}

Related Tutorials