首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#中实现glob

在C#中实现glob(全局匹配)的一种方法是使用正则表达式(Regular Expression)。以下是一个简单的示例,展示了如何在C#中使用正则表达式来实现glob匹配:

代码语言:csharp
复制
using System;
using System.Text.RegularExpressions;

public class GlobMatcher
{
    public static void Main(string[] args)
    {
        string pattern = "*.txt";
        string input = "hello.txt";

        bool isMatch = IsGlobMatch(pattern, input);
        Console.WriteLine($"Is '{input}' matched by '{pattern}'? {isMatch}");
    }

    public static bool IsGlobMatch(string pattern, string input)
    {
        string regexPattern = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";
        return Regex.IsMatch(input, regexPattern, RegexOptions.IgnoreCase);
    }
}

在这个示例中,我们定义了一个名为IsGlobMatch的方法,它接受两个字符串参数:patterninput。我们首先使用Regex.Escape方法转义pattern中的特殊字符,然后将*替换为.*替换为.。最后,我们使用Regex.IsMatch方法检查input是否与生成的正则表达式匹配。

在这个示例中,我们使用了RegexOptions.IgnoreCase来忽略大小写。如果您希望匹配区分大小写,请删除该选项。

这只是实现glob匹配的一种方法,您可以根据自己的需求进行调整。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券