C#代码片段需要复制VBA Like运算符 [英] C# snippet needed to replicate VBA Like operator

查看:122
本文介绍了C#代码片段需要复制VBA Like运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在

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

在所有情况下,模式仅*使用通配符的任何字符串(包括空字符串)匹配。 VBA中的Like运营商的产量只有真/假结果,所以它的到后来的VBA代码来进一步解析和挖出的匹配子,只要有一个匹配。

In all cases the patterns use only the * wildcard which matches any string (including the empty string). The VBA Like operator yields only a true/false result so it's up to the subsequent VBA code to parse further and pluck out the matching substrings whenever there's a match.

我d是非常感激,如果有人可以提供C#代码片段来测试相同类型的简单通配符匹配的。如果片断也产生匹配的子 - 甚至更好

I'd be most appreciative if someone can provide a C# snippet to test for the same type of simple wildcard match. If the snippet also yields matching substrings - even better.

推荐答案

好吧,那特定的模式可以与匹配

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

在MSDN的正则表达式语言元素页面是.NET正则表达式一个很好的参考。

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

这篇关于C#代码片段需要复制VBA Like运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆