比较字符串

时间:2014-11-11 08:34:38

标签: c# string

如果字符串a喜欢字符串b形式,是否有任何方法允许我们返回true?

考试:

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

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

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用正则表达式

使用以下功能
Regex.IsMatch("string", "your expression") 

以下行的实例应返回true

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

注意:这样您每次都需要为不同格式创建exp

答案 1 :(得分:0)

您可以使用以下方法检查给定字符串是否与带有通配符的类似DOS的模式匹配(即一个模式表示一个字符带'?',零个或多个字符带'*'):

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

您可以这样称呼它:

bool match = IsMatch("what is your name?", "*is*name*?"); // Returns true

答案 2 :(得分:0)

您可以使用以下 not-optimized 方法。该功能可能没有考虑到某些情况,但我认为它给你一个起点。

另一种可能的解决方案是正则表达式

        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;
        }

祝你好运

相关问题