2

Is there any method that allow us to return true if string a likes string b formality?

Exam:

 "12:2".Like("*:*") = true

or

 "what is your name?".Like("*is*name*?")=true

Thanks!

3 Answers3

2

You can use this following function using Regular Expression

Regex.IsMatch("string", "your expression") 

Instance following line should return true:

Regex.IsMatch("12:2", "/[0-9]{2,}:[0-9]{1,}/") 

Note: This way you have to create exp every time for different format

Manwal
  • 23,450
  • 12
  • 63
  • 93
0

You can use the following method to check whether a given string matches a DOS like pattern with wildcards (i.e. a pattern that denotes one character with '?' and zero or more characters with '*'):

public static bool IsMatch(string str, string pattern)
{
    string regexString = "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
    Regex regex = new Regex(regexString);
    return regex.IsMatch(regexString);
}

You can call it like this:

bool match = IsMatch("what is your name?", "*is*name*?"); // Returns true
Pavel Vladov
  • 4,707
  • 3
  • 35
  • 39
0

You can use the following not-optimized method. The function may does not take into account some cases, but i think it gives you a point to start from.

Another possible solution is to you Regular Expressions

        public static bool Like(string pattern, string str)
        {
            string[] words = pattern.Split('*').Where(w => w.Trim() != string.Empty).ToArray();

            List<int> indeces = new List<int>();

            for (int i = 0, l = words.Length; i < l; i++)
            {
                int wordIndex = str.IndexOf(words[i], StringComparison.OrdinalIgnoreCase);

                if (wordIndex == -1)
                    return false;
                else
                    indeces.Add(wordIndex);
            }

            List<int> sortedIndeces = indeces.ToList();
            sortedIndeces.Sort();

            for (int i = 0, l = sortedIndeces.Count; i < l; i++)
            {
                if (sortedIndeces[i] != indeces[i]) return false;
            }

            return true;
        }

Good Luck

Oday Fraiwan
  • 1,147
  • 1
  • 9
  • 21