C# Version Of SQL LIKE

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

    As aready proposed in this answer and this other answer Microsoft.VisualBasic.CompilerServices.Operators.LikeString could be a good option for simple tasks, when a RegExp is overkill. Syntax is different from RegExp and SQL LIKE operator, but it's really simple to learn (mainly because it's also very limited).

    Assembly Microsoft.VisualBasic must be added as a reference to the project to use this method.

    For more information see Operators.LikeString Method and for a description of the syntax see Like Operator (Visual Basic).

    It can be used as an extension method to String class:

    /// 
    /// Visual Basic like operator. Performs simple, case insensitive, string pattern matching.
    /// 
    /// 
    ///  ? = Any single character. * = Zero or more characters. # = Any single digit (0–9)
    /// true if the string matches the pattern
    public static bool Like(this string thisString, string pattern)
        => Microsoft.VisualBasic.CompilerServices.Operators
            .LikeString(thisString, pattern, Microsoft.VisualBasic.CompareMethod.Text);
    

提交回复
热议问题