복붙노트

[SQL] SQL LIKE의 C # 버전

SQL

SQL LIKE의 C # 버전

C #에서 문자열의 패턴을 검색 할 수있는 방법이 있습니까?

는 SQL LIKE 같은 뭔가 매우 유용 할 것입니다.

해결법

  1. ==============================

    1.정규 표현식은 LIKE 훨씬 더 허용하고, 모든 것이 허용하지만, 완전히 다른 문법을 가지고있다. LIKE에 대한 규칙은 매우 간단하기 때문에, (% 수단은 제로 또는-이상의 문자와 _ 수단을 하나 개의 문자 임)와 LIKE의 인수와 정규 표현식 모두 문자열로 표현된다, 우리는 LIKE 인수를 정규 표현식을 만들 수 있습니다 (예 abc_ef % * USD) 및 해당 일반 식으로 바꿀 (예 \ Aabc.ef. * \ USD * \ z) :

    정규 표현식은 LIKE 훨씬 더 허용하고, 모든 것이 허용하지만, 완전히 다른 문법을 가지고있다. LIKE에 대한 규칙은 매우 간단하기 때문에, (% 수단은 제로 또는-이상의 문자와 _ 수단을 하나 개의 문자 임)와 LIKE의 인수와 정규 표현식 모두 문자열로 표현된다, 우리는 LIKE 인수를 정규 표현식을 만들 수 있습니다 (예 abc_ef % * USD) 및 해당 일반 식으로 바꿀 (예 \ Aabc.ef. * \ USD * \ z) :

    @"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z"
    

    우리가 같이 () 메소드를 구축 할 수있는 사람 :

    public static class MyStringExtensions
    {
      public static bool Like(this string toSearch, string toFind)
      {
        return new Regex(@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z", RegexOptions.Singleline).IsMatch(toSearch);
      }
    }
    

    따라서 :

    bool willBeTrue = "abcdefg".Like("abcd_fg");
    bool willAlsoBeTrue = "abcdefg".Like("ab%f%");
    bool willBeFalse = "abcdefghi".Like("abcd_fg");
    
  2. ==============================

    2.당신은 C #에서 SQL의 "LIKE"연산자로 검색 할 수있는 방법이 몇 가지 있습니다. 그냥 패턴이 문자열 변수에 있는지 여부를 알고 싶은 경우에, 당신은 사용할 수 있습니다

    당신은 C #에서 SQL의 "LIKE"연산자로 검색 할 수있는 방법이 몇 가지 있습니다. 그냥 패턴이 문자열 변수에 있는지 여부를 알고 싶은 경우에, 당신은 사용할 수 있습니다

    string value = "samplevalue";
            value.Contains("eva"); // like '%eva%'
             value.StartsWith("eva");  // like 'eva%'
            value.EndsWith("eva"); // like '%eva'
    

    당신은 문자열의 목록에서 패턴을 검색 할 경우, 당신은 개체의 특징에 LINQ를 사용해야합니다.

                List<string> valuee = new List<string> { "samplevalue1", "samplevalue2", "samplevalue3" };
            List<string> contains = (List<string>) (from val in valuee
                                            where val.Contains("pattern")
                                            select val); // like '%pattern%'
    
            List<string> starts = (List<string>) (from val in valuee
                                          where val.StartsWith("pattern")
                                          select val);// like 'pattern%'
    
            List<string> ends = (List<string>) (from val in valuee                          
                                        where val.EndsWith ("pattern")
                                        select val);// like '%pattern'
    
  3. ==============================

    3.나는 계약이 우연히 때, 나는 100 % 준수 트랜 잭트 SQL LIKE 기능을하는 것보다 다른 옵션이 없었다. 정적 기능과 문자열 확장 방법 - 아래는 결과입니다. 나는 그것이 더 최적화 할 수 있습니다 확신 해요,하지만 꽤 빨리 그리고 테스트 시나리오의 내 긴 목록을 통과시켰다. 누군가가 도움이되기를 바랍니다!

    나는 계약이 우연히 때, 나는 100 % 준수 트랜 잭트 SQL LIKE 기능을하는 것보다 다른 옵션이 없었다. 정적 기능과 문자열 확장 방법 - 아래는 결과입니다. 나는 그것이 더 최적화 할 수 있습니다 확신 해요,하지만 꽤 빨리 그리고 테스트 시나리오의 내 긴 목록을 통과시켰다. 누군가가 도움이되기를 바랍니다!

    using System;
    using System.Collections.Generic;
    
    namespace SqlLikeSample
    {
        public class TestSqlLikeFunction
        {
            static void Main(string[] args)
            {
                TestSqlLikePattern(true, "%", "");
                TestSqlLikePattern(true, "%", " ");
                TestSqlLikePattern(true, "%", "asdfa asdf asdf");
                TestSqlLikePattern(true, "%", "%");
                TestSqlLikePattern(false, "_", "");
                TestSqlLikePattern(true, "_", " ");
                TestSqlLikePattern(true, "_", "4");
                TestSqlLikePattern(true, "_", "C");
                TestSqlLikePattern(false, "_", "CX");
                TestSqlLikePattern(false, "[ABCD]", "");
                TestSqlLikePattern(true, "[ABCD]", "A");
                TestSqlLikePattern(true, "[ABCD]", "b");
                TestSqlLikePattern(false, "[ABCD]", "X");
                TestSqlLikePattern(false, "[ABCD]", "AB");
                TestSqlLikePattern(true, "[B-D]", "C");
                TestSqlLikePattern(true, "[B-D]", "D");
                TestSqlLikePattern(false, "[B-D]", "A");
                TestSqlLikePattern(false, "[^B-D]", "C");
                TestSqlLikePattern(false, "[^B-D]", "D");
                TestSqlLikePattern(true, "[^B-D]", "A");
                TestSqlLikePattern(true, "%TEST[ABCD]XXX", "lolTESTBXXX");
                TestSqlLikePattern(false, "%TEST[ABCD]XXX", "lolTESTZXXX");
                TestSqlLikePattern(false, "%TEST[^ABCD]XXX", "lolTESTBXXX");
                TestSqlLikePattern(true, "%TEST[^ABCD]XXX", "lolTESTZXXX");
                TestSqlLikePattern(true, "%TEST[B-D]XXX", "lolTESTBXXX");
                TestSqlLikePattern(true, "%TEST[^B-D]XXX", "lolTESTZXXX");
                TestSqlLikePattern(true, "%Stuff.txt", "Stuff.txt");
                TestSqlLikePattern(true, "%Stuff.txt", "MagicStuff.txt");
                TestSqlLikePattern(false, "%Stuff.txt", "MagicStuff.txt.img");
                TestSqlLikePattern(false, "%Stuff.txt", "Stuff.txt.img");
                TestSqlLikePattern(false, "%Stuff.txt", "MagicStuff001.txt.img");
                TestSqlLikePattern(true, "Stuff.txt%", "Stuff.txt");
                TestSqlLikePattern(false, "Stuff.txt%", "MagicStuff.txt");
                TestSqlLikePattern(false, "Stuff.txt%", "MagicStuff.txt.img");
                TestSqlLikePattern(true, "Stuff.txt%", "Stuff.txt.img");
                TestSqlLikePattern(false, "Stuff.txt%", "MagicStuff001.txt.img");
                TestSqlLikePattern(true, "%Stuff.txt%", "Stuff.txt");
                TestSqlLikePattern(true, "%Stuff.txt%", "MagicStuff.txt");
                TestSqlLikePattern(true, "%Stuff.txt%", "MagicStuff.txt.img");
                TestSqlLikePattern(true, "%Stuff.txt%", "Stuff.txt.img");
                TestSqlLikePattern(false, "%Stuff.txt%", "MagicStuff001.txt.img");
                TestSqlLikePattern(true, "%Stuff%.txt", "Stuff.txt");
                TestSqlLikePattern(true, "%Stuff%.txt", "MagicStuff.txt");
                TestSqlLikePattern(false, "%Stuff%.txt", "MagicStuff.txt.img");
                TestSqlLikePattern(false, "%Stuff%.txt", "Stuff.txt.img");
                TestSqlLikePattern(false, "%Stuff%.txt", "MagicStuff001.txt.img");
                TestSqlLikePattern(true, "%Stuff%.txt", "MagicStuff001.txt");
                TestSqlLikePattern(true, "Stuff%.txt%", "Stuff.txt");
                TestSqlLikePattern(false, "Stuff%.txt%", "MagicStuff.txt");
                TestSqlLikePattern(false, "Stuff%.txt%", "MagicStuff.txt.img");
                TestSqlLikePattern(true, "Stuff%.txt%", "Stuff.txt.img");
                TestSqlLikePattern(false, "Stuff%.txt%", "MagicStuff001.txt.img");
                TestSqlLikePattern(false, "Stuff%.txt%", "MagicStuff001.txt");
                TestSqlLikePattern(true, "%Stuff%.txt%", "Stuff.txt");
                TestSqlLikePattern(true, "%Stuff%.txt%", "MagicStuff.txt");
                TestSqlLikePattern(true, "%Stuff%.txt%", "MagicStuff.txt.img");
                TestSqlLikePattern(true, "%Stuff%.txt%", "Stuff.txt.img");
                TestSqlLikePattern(true, "%Stuff%.txt%", "MagicStuff001.txt.img");
                TestSqlLikePattern(true, "%Stuff%.txt%", "MagicStuff001.txt");
                TestSqlLikePattern(true, "_Stuff_.txt_", "1Stuff3.txt4");
                TestSqlLikePattern(false, "_Stuff_.txt_", "1Stuff.txt4");
                TestSqlLikePattern(false, "_Stuff_.txt_", "1Stuff3.txt");
                TestSqlLikePattern(false, "_Stuff_.txt_", "Stuff3.txt4");
    
                Console.ReadKey();
            }
    
            public static void TestSqlLikePattern(bool expectedResult, string pattern, string testString)
            {
                bool result = testString.SqlLike(pattern);
                if (expectedResult != result)
                {
                    Console.ForegroundColor = ConsoleColor.Red; System.Console.Out.Write("[SqlLike] FAIL");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green; Console.Write("[SqlLike] PASS");
                }
                Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(": \"" + testString + "\" LIKE \"" + pattern + "\" == " + expectedResult);
            }
        }
    
        public static class SqlLikeStringExtensions
        {
            public static bool SqlLike(this string s, string pattern)
            {
                return SqlLikeStringUtilities.SqlLike(pattern, s);
            }
        }
    
        public static class SqlLikeStringUtilities
        {
            public static bool SqlLike(string pattern, string str)
            {
                bool isMatch = true,
                    isWildCardOn = false,
                    isCharWildCardOn = false,
                    isCharSetOn = false,
                    isNotCharSetOn = false,
                    endOfPattern = false;
                int lastWildCard = -1;
                int patternIndex = 0;
                List<char> set = new List<char>();
                char p = '\0';
    
                for (int i = 0; i < str.Length; i++)
                {
                    char c = str[i];
                    endOfPattern = (patternIndex >= pattern.Length);
                    if (!endOfPattern)
                    {
                        p = pattern[patternIndex];
    
                        if (!isWildCardOn && p == '%')
                        {
                            lastWildCard = patternIndex;
                            isWildCardOn = true;
                            while (patternIndex < pattern.Length &&
                                pattern[patternIndex] == '%')
                            {
                                patternIndex++;
                            }
                            if (patternIndex >= pattern.Length) p = '\0';
                            else p = pattern[patternIndex];
                        }
                        else if (p == '_')
                        {
                            isCharWildCardOn = true;
                            patternIndex++;
                        }
                        else if (p == '[')
                        {
                            if (pattern[++patternIndex] == '^')
                            {
                                isNotCharSetOn = true;
                                patternIndex++;
                            }
                            else isCharSetOn = true;
    
                            set.Clear();
                            if (pattern[patternIndex + 1] == '-' && pattern[patternIndex + 3] == ']')
                            {
                                char start = char.ToUpper(pattern[patternIndex]);
                                patternIndex += 2;
                                char end = char.ToUpper(pattern[patternIndex]);
                                if (start <= end)
                                {
                                    for (char ci = start; ci <= end; ci++)
                                    {
                                        set.Add(ci);
                                    }
                                }
                                patternIndex++;
                            }
    
                            while (patternIndex < pattern.Length &&
                                pattern[patternIndex] != ']')
                            {
                                set.Add(pattern[patternIndex]);
                                patternIndex++;
                            }
                            patternIndex++;
                        }
                    }
    
                    if (isWildCardOn)
                    {
                        if (char.ToUpper(c) == char.ToUpper(p))
                        {
                            isWildCardOn = false;
                            patternIndex++;
                        }
                    }
                    else if (isCharWildCardOn)
                    {
                        isCharWildCardOn = false;
                    }
                    else if (isCharSetOn || isNotCharSetOn)
                    {
                        bool charMatch = (set.Contains(char.ToUpper(c)));
                        if ((isNotCharSetOn && charMatch) || (isCharSetOn && !charMatch))
                        {
                            if (lastWildCard >= 0) patternIndex = lastWildCard;
                            else
                            {
                                isMatch = false;
                                break;
                            }
                        }
                        isNotCharSetOn = isCharSetOn = false;
                    }
                    else
                    {
                        if (char.ToUpper(c) == char.ToUpper(p))
                        {
                            patternIndex++;
                        }
                        else
                        {
                            if (lastWildCard >= 0) patternIndex = lastWildCard;
                            else
                            {
                                isMatch = false;
                                break;
                            }
                        }
                    }
                }
                endOfPattern = (patternIndex >= pattern.Length);
    
                if (isMatch && !endOfPattern)
                {
                    bool isOnlyWildCards = true;
                    for (int i = patternIndex; i < pattern.Length; i++)
                    {
                        if (pattern[i] != '%')
                        {
                            isOnlyWildCards = false;
                            break;
                        }
                    }
                    if (isOnlyWildCards) endOfPattern = true;
                }
                return isMatch && endOfPattern;
            }
        }
    }
    
  4. ==============================

    4.( "someString")를 myString.Contain; //이 mystring에 LIKE '% someString %'과 동등 myString.EndWith ( "someString"); // mystring에 LIKE '%의 someString'과 동등 myString.StartWith ( "someString"); // mystring에 LIKE 'someString %의'과 동등

    ( "someString")를 myString.Contain; //이 mystring에 LIKE '% someString %'과 동등 myString.EndWith ( "someString"); // mystring에 LIKE '%의 someString'과 동등 myString.StartWith ( "someString"); // mystring에 LIKE 'someString %의'과 동등

  5. ==============================

    5.간단히 .Contains ()는 당신을 위해 일을 할 것입니다.

    간단히 .Contains ()는 당신을 위해 일을 할 것입니다.

    "Example String".Contains("amp");   //like '%amp%'
    

    이 사실 반환하고, 그 위에 선택을 수행하면 원하는 출력을 반환합니다.

  6. ==============================

    6.Operators.LikeString

    Operators.LikeString

    https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.operators.likestring(v=vs.100).ASPX

    public static bool LikeString(
        string Source,
        string Pattern,
        CompareMethod CompareOption
    )
    
  7. ==============================

    7.당신은 시도 해 봤나

    당신은 시도 해 봤나

    "This is a string".Contains("string");
    
  8. ==============================

    8.어쩌면 포함

    어쩌면 포함

    if ("bla bli blu".Contains("blu")){......}
    
  9. ==============================

    9.어떻게 Linq는에서 SQL처럼의 %를 수행하는 -이 질문을 확인?

    어떻게 Linq는에서 SQL처럼의 %를 수행하는 -이 질문을 확인?

    또한, 고급 문자열 패턴 검색을 위해, 정규 표현식을 사용하는 방법에 대한 자습서 많이 있습니다 - 예를 들어, http://www.codeproject.com/KB/dotnet/regextutorial.aspx

  10. ==============================

    10.정규 표현식을 확인하십시오.

    정규 표현식을 확인하십시오.

  11. ==============================

    11.이처럼 사용

    이처럼 사용

    if (lbl.Text.StartWith("hr")==true ) {…}
    
  12. ==============================

    12.SQL LIKE 연산자에 LINQ

    SQL LIKE 연산자에 LINQ

  13. ==============================

    13.나는이 내용은 "string.Contains ("STR ")를 사용할 수 있다고 생각합니다.

    나는이 내용은 "string.Contains ("STR ")를 사용할 수 있다고 생각합니다.

    이 패턴에 문자열에서 검색 및 설립 진실과 거짓 그렇지 않은 경우 발생합니다.

  14. ==============================

    14.늦은하지만 적절한 대답으로 :

    늦은하지만 적절한 대답으로 :

    C-샤프의 SQL과 같은 기능에가 가장 가까운 것은 C #에서 SQL과 유사한 기능의 구현입니다.

    당신의 그것을 찢어 수 있습니다 http://code.google.com/p/csharp-sqlite/source/checkout [루트] /csharp-sqlite/Community.CsharpSqlite/src/func_c.cs

        /*
    ** Implementation of the like() SQL function.  This function implements
    ** the build-in LIKE operator.  The first argument to the function is the
    ** pattern and the second argument is the string.  So, the SQL statements:
    **
    **       A LIKE B
    **
    ** is implemented as like(B,A).
    **
    ** This same function (with a different compareInfo structure) computes
    ** the GLOB operator.
    */
        static void likeFunc(
        sqlite3_context context,
        int argc,
        sqlite3_value[] argv
        )
        {
          string zA, zB;
          u32 escape = 0;
          int nPat;
          sqlite3 db = sqlite3_context_db_handle( context );
    
          zB = sqlite3_value_text( argv[0] );
          zA = sqlite3_value_text( argv[1] );
    
          /* Limit the length of the LIKE or GLOB pattern to avoid problems
          ** of deep recursion and N*N behavior in patternCompare().
          */
          nPat = sqlite3_value_bytes( argv[0] );
          testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
          testcase( nPat == db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] + 1 );
          if ( nPat > db.aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] )
          {
            sqlite3_result_error( context, "LIKE or GLOB pattern too complex", -1 );
            return;
          }
          //Debug.Assert( zB == sqlite3_value_text( argv[0] ) );  /* Encoding did not change */
    
          if ( argc == 3 )
          {
            /* The escape character string must consist of a single UTF-8 character.
            ** Otherwise, return an error.
            */
            string zEsc = sqlite3_value_text( argv[2] );
            if ( zEsc == null )
              return;
            if ( sqlite3Utf8CharLen( zEsc, -1 ) != 1 )
            {
              sqlite3_result_error( context,
              "ESCAPE expression must be a single character", -1 );
              return;
            }
            escape = sqlite3Utf8Read( zEsc, ref zEsc );
          }
          if ( zA != null && zB != null )
          {
            compareInfo pInfo = (compareInfo)sqlite3_user_data( context );
    #if SQLITE_TEST
    #if !TCLSH
            sqlite3_like_count++;
    #else
            sqlite3_like_count.iValue++;
    #endif
    #endif
            sqlite3_result_int( context, patternCompare( zB, zA, pInfo, escape ) ? 1 : 0 );
          }
        }
    
    
    
    
        /*
        ** Compare two UTF-8 strings for equality where the first string can
        ** potentially be a "glob" expression.  Return true (1) if they
        ** are the same and false (0) if they are different.
        **
        ** Globbing rules:
        **
        **      '*'       Matches any sequence of zero or more characters.
        **
        **      '?'       Matches exactly one character.
        **
        **     [...]      Matches one character from the enclosed list of
        **                characters.
        **
        **     [^...]     Matches one character not in the enclosed list.
        **
        ** With the [...] and [^...] matching, a ']' character can be included
        ** in the list by making it the first character after '[' or '^'.  A
        ** range of characters can be specified using '-'.  Example:
        ** "[a-z]" matches any single lower-case letter.  To match a '-', make
        ** it the last character in the list.
        **
        ** This routine is usually quick, but can be N**2 in the worst case.
        **
        ** Hints: to match '*' or '?', put them in "[]".  Like this:
        **
        **         abc[*]xyz        Matches "abc*xyz" only
        */
        static bool patternCompare(
        string zPattern,            /* The glob pattern */
        string zString,             /* The string to compare against the glob */
        compareInfo pInfo,          /* Information about how to do the compare */
        u32 esc                     /* The escape character */
        )
        {
          u32 c, c2;
          int invert;
          int seen;
          int matchOne = (int)pInfo.matchOne;
          int matchAll = (int)pInfo.matchAll;
          int matchSet = (int)pInfo.matchSet;
          bool noCase = pInfo.noCase;
          bool prevEscape = false;     /* True if the previous character was 'escape' */
          string inPattern = zPattern; //Entered Pattern
    
          while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) != 0 )
          {
            if ( !prevEscape && c == matchAll )
            {
              while ( ( c = sqlite3Utf8Read( zPattern, ref zPattern ) ) == matchAll
              || c == matchOne )
              {
                if ( c == matchOne && sqlite3Utf8Read( zString, ref zString ) == 0 )
                {
                  return false;
                }
              }
              if ( c == 0 )
              {
                return true;
              }
              else if ( c == esc )
              {
                c = sqlite3Utf8Read( zPattern, ref zPattern );
                if ( c == 0 )
                {
                  return false;
                }
              }
              else if ( c == matchSet )
              {
                Debug.Assert( esc == 0 );         /* This is GLOB, not LIKE */
                Debug.Assert( matchSet < 0x80 );  /* '[' is a single-byte character */
                int len = 0;
                while ( len < zString.Length && patternCompare( inPattern.Substring( inPattern.Length - zPattern.Length - 1 ), zString.Substring( len ), pInfo, esc ) == false )
                {
                  SQLITE_SKIP_UTF8( zString, ref len );
                }
                return len < zString.Length;
              }
              while ( ( c2 = sqlite3Utf8Read( zString, ref zString ) ) != 0 )
              {
                if ( noCase )
                {
                   if( 0==((c2)&~0x7f) )
                    c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2);
                   if ( 0 == ( ( c ) & ~0x7f ) )
                     c = (u32)sqlite3UpperToLower[c]; //GlogUpperToLower(c);
                  while ( c2 != 0 && c2 != c )
                  {
                    c2 = sqlite3Utf8Read( zString, ref zString );
                    if ( 0 == ( ( c2 ) & ~0x7f ) )
                      c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2);
                  }
                }
                else
                {
                  while ( c2 != 0 && c2 != c )
                  {
                    c2 = sqlite3Utf8Read( zString, ref zString );
                  }
                }
                if ( c2 == 0 )
                  return false;
                if ( patternCompare( zPattern, zString, pInfo, esc ) )
                  return true;
              }
              return false;
            }
            else if ( !prevEscape && c == matchOne )
            {
              if ( sqlite3Utf8Read( zString, ref zString ) == 0 )
              {
                return false;
              }
            }
            else if ( c == matchSet )
            {
              u32 prior_c = 0;
              Debug.Assert( esc == 0 );    /* This only occurs for GLOB, not LIKE */
              seen = 0;
              invert = 0;
              c = sqlite3Utf8Read( zString, ref zString );
              if ( c == 0 )
                return false;
              c2 = sqlite3Utf8Read( zPattern, ref zPattern );
              if ( c2 == '^' )
              {
                invert = 1;
                c2 = sqlite3Utf8Read( zPattern, ref zPattern );
              }
              if ( c2 == ']' )
              {
                if ( c == ']' )
                  seen = 1;
                c2 = sqlite3Utf8Read( zPattern, ref zPattern );
              }
              while ( c2 != 0 && c2 != ']' )
              {
                if ( c2 == '-' && zPattern[0] != ']' && zPattern[0] != 0 && prior_c > 0 )
                {
                  c2 = sqlite3Utf8Read( zPattern, ref zPattern );
                  if ( c >= prior_c && c <= c2 )
                    seen = 1;
                  prior_c = 0;
                }
                else
                {
                  if ( c == c2 )
                  {
                    seen = 1;
                  }
                  prior_c = c2;
                }
                c2 = sqlite3Utf8Read( zPattern, ref zPattern );
              }
              if ( c2 == 0 || ( seen ^ invert ) == 0 )
              {
                return false;
              }
            }
            else if ( esc == c && !prevEscape )
            {
              prevEscape = true;
            }
            else
            {
              c2 = sqlite3Utf8Read( zString, ref zString );
              if ( noCase )
              {
                if ( c < 0x80 )
                  c = (u32)sqlite3UpperToLower[c]; //GlogUpperToLower(c);
                if ( c2 < 0x80 )
                  c2 = (u32)sqlite3UpperToLower[c2]; //GlogUpperToLower(c2);
              }
              if ( c != c2 )
              {
                return false;
              }
              prevEscape = false;
            }
          }
          return zString.Length == 0;
        }
    
  15. ==============================

    15.이것은 내 구현 -이 테스트를 통과 트릭 않습니다 - 당신은 당신의 문에 세 물결표를 사용하는 경우 교체가 토큰을 변경할 수 있습니다 :

    이것은 내 구현 -이 테스트를 통과 트릭 않습니다 - 당신은 당신의 문에 세 물결표를 사용하는 경우 교체가 토큰을 변경할 수 있습니다 :

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

    예:

    // 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
    }
    
  16. ==============================

    16.

    public static class StringsEx
    {
        public static IEnumerable<String> Like(this IEnumerable<String> input, String pattern)
        {
            var dt = new DataTable();
            dt.Columns.Add("Search");
            foreach (String str in input)
            {
                dt.Rows.Add(str);
            }
            dt.DefaultView.RowFilter = String.Format("Search LIKE '{0}'", pattern);
            return dt.DefaultView.ToTable()
                .AsEnumerable()
                .Select(r => r.Field<String>("Search"));
        }
    }
    

    유일한 단점은 다음과 같은있다 : "와일드 카드 문자는 문자열의 중간에 허용되지 않습니다 예를 들어, '테 *의 XT'는 허용되지 않습니다.."©

  17. ==============================

    17.몇 가지 좋은 답변은 여기에있다. 여기 올바른 이미 무엇인지 요약 : 사용 포함, 대부분의 요구에 좋은 답변입니다 endswith startswith을. 정규 표현식은 고급 요구에 원하는 수 있습니다.

    몇 가지 좋은 답변은 여기에있다. 여기 올바른 이미 무엇인지 요약 : 사용 포함, 대부분의 요구에 좋은 답변입니다 endswith startswith을. 정규 표현식은 고급 요구에 원하는 수 있습니다.

    이 답변에 언급되지 뭔가하지만, 문자열의 수집, LINQ는 어디 메소드에 호출이 필터를 적용하는 데 사용할 수 있다는 점이다.

  18. ==============================

    18.VB.NET DLL은 VB.NET처럼 운영자 캡슐화 추가

    VB.NET DLL은 VB.NET처럼 운영자 캡슐화 추가

  19. ==============================

    19.로이 답변에서 제안 aready과 정규식이 잔인한 때 다른 응답 Microsoft.VisualBasic.CompilerServices.Operators.LikeString은 간단한 작업을위한 좋은 옵션이 될 수 있습니다. 구문 정규식 및 SQL LIKE 연산자는 다른, 그러나 (그것은 또한 매우 제한있어 주로하기 때문에) 배우기 정말 간단합니다.

    로이 답변에서 제안 aready과 정규식이 잔인한 때 다른 응답 Microsoft.VisualBasic.CompilerServices.Operators.LikeString은 간단한 작업을위한 좋은 옵션이 될 수 있습니다. 구문 정규식 및 SQL LIKE 연산자는 다른, 그러나 (그것은 또한 매우 제한있어 주로하기 때문에) 배우기 정말 간단합니다.

    조립 Microsoft.VisualBasic은이 방법을 사용하려면 프로젝트에 참조로 추가해야합니다.

    자세한 내용은 Operators.LikeString 방법을 참조 및 구문에 대한 자세한 내용은 LIKE 연산자 (Visual Basic)를 참조하십시오.

    그것은 String 클래스의 확장 방법으로 사용할 수 있습니다 :

    /// <summary>
    /// Visual Basic like operator. Performs simple, case insensitive, string pattern matching.
    /// </summary>
    /// <param name="thisString"></param>
    /// <param name="pattern"> ? = Any single character. * = Zero or more characters. # = Any single digit (0–9)</param>
    /// <returns>true if the string matches the pattern</returns>
    public static bool Like(this string thisString, string pattern)
        => Microsoft.VisualBasic.CompilerServices.Operators
            .LikeString(thisString, pattern, Microsoft.VisualBasic.CompareMethod.Text);
    
  20. from https://stackoverflow.com/questions/5417070/c-sharp-version-of-sql-like by cc-by-sa and MIT license