C# Version Of SQL LIKE

后端 未结 20 2143
天涯浪人
天涯浪人 2020-11-29 02:12

Is there any way to search patterns in strings in C#?

Something like Sql LIKE would be very useful.

相关标签:
20条回答
  • 2020-11-29 02:21

    Linq to SQL Like Operator

    0 讨论(0)
  • 2020-11-29 02:23

    there are several good answers here. to summarize what is already here and correct: using contains, startswith, endswith are good answers for most needs. regular expressions are what you want for more advanced needs.

    something that is not mentioned in these answers, though, is that for a collection of strings, linq can be used to apply these filters in a call to the where method.

    0 讨论(0)
  • 2020-11-29 02:24

    Have your tried

    "This is a string".Contains("string");
    
    0 讨论(0)
  • 2020-11-29 02:24

    This is my implementation - it passes the tests and does the trick - you may want to change the replacement token if you're using three tildes in your statements:

    private Regex LikeExpressionToRegexPattern(String likePattern)
    {
        var replacementToken = "~~~";
    
        String result = likePattern.Replace("_", replacementToken)
            .Replace("%", ".*");
    
        result = Regex.Replace(result, @"\[.*" + replacementToken + @".*\]", "_");
    
        result = result.Replace(replacementToken, ".");
    
        return new Regex("^" + result + "$", RegexOptions.IgnoreCase);
    }
    

    Example:

    // Define a test string.
    string text = "Hello stackoverflow world";
    
    string like = "%flow%";
    
    // Define a regular expression and Find matches.
    MatchCollection matches = LikeExpressionToRegexPattern(like).Matches(text);
    
    //Result.
    if (matches.Count > 0) {
        //Yes
    } else {
        //No
    }
    
    0 讨论(0)
  • 2020-11-29 02:25

    Add a VB.NET DLL encapsulating the VB.NET Like Operator

    0 讨论(0)
  • 2020-11-29 02:25
    public static bool Like(this string value, string pattern)
    {
        if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(pattern))
            return false;
    
        bool valid = true;
        string[] words = pattern.Split("*");
        int counter = words.Count();
    
        for (int i = 0; i < counter; i++)
        {
            valid = valid && value.StartsWith(words[i]);                
            value = value.Substring(words[i].Length);
        }
        return valid;
     }
    
    0 讨论(0)
提交回复
热议问题