C# Version Of SQL LIKE

后端 未结 20 2232
天涯浪人
天涯浪人 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: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
    }
    

提交回复
热议问题