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!

7
  • 9
    No but you can have a look at regular expressions Commented Nov 11, 2014 at 8:35
  • Regex is what you need Commented Nov 11, 2014 at 8:36
  • is "*" your only operator here? Commented Nov 11, 2014 at 8:36
  • 2
    use regex or use VB.NET and it's Like-operator Commented Nov 11, 2014 at 8:38
  • possible duplicate of Need to perform Wildcard (*,?, etc) search on a string using Regex Commented Nov 11, 2014 at 8:41

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.