C# snippet needed to replicate VBA Like operator

后端 未结 3 1508
一向
一向 2021-01-12 14:46

I am converting VBA code that contains the LIKE operator, as in

    dim sToken as String
    if sToken Like \"(*,*)\" then ...

In all case

相关标签:
3条回答
  • 2021-01-12 15:39

    If you want some stellar matching power, I suggest getting into Regular Expressions.

    0 讨论(0)
  • 2021-01-12 15:46

    Several people have suggested regular expressions which should work well for this scenario. Another option is to use the VB Like operator directly from C# code. This can be done by invoking the Compiler helper LikeOperator.LikeString. This function is located in the VB runtime assembly, Microsoft.VisualBasic.dll, and is usable from C#.

    using Microsoft.VisualBasic.CompilerServices;
    
    ...
    
    if (LikeOperator.LikeString(sToken, "(*,*)")) { 
      ...
    }
    

    I don't believe this version has 100% parity with the VBA version of Like but it will be extremely close and will match for the common scenarios.

    0 讨论(0)
  • 2021-01-12 15:47

    Well, that particular pattern could be matched with

    if (sToken.StartsWith("(") && sToken.EndsWith(")")
        && sToken.Contains(","))
    

    but in general you may find it makes more sense to use regular expressions. For example:

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
        static void Main(string[] args)
        {
            Regex regex = new Regex(@"^\(.*,.*\)$");
    
            Console.WriteLine(regex.IsMatch("x(a,b)")); // False due to the x
            Console.WriteLine(regex.IsMatch("(a,b)x")); // False due to the x
            Console.WriteLine(regex.IsMatch("(ab)"));   // False due to the lack of ,
            Console.WriteLine(regex.IsMatch("(a,b"));   // False due to the lack of )
            Console.WriteLine(regex.IsMatch("(a,b)"));   // True!
            Console.WriteLine(regex.IsMatch("(aaa,bbb)"));   // True!
            Console.WriteLine(regex.IsMatch("(,)"));   // True!
        }
    }
    

    Things to note with the pattern here:

    • I've used a verbatim string literal (the @ at the start) to make it easier to perform escaping within the regex
    • ^ and $ force it to match the whole string
    • The brackets are escaped so they're not treated as grouping operators

    The MSDN "Regular Expression Language Elements" page is a good reference for .NET regexes.

    0 讨论(0)
提交回复
热议问题