首页 > 解决方案 > c# 正则表达式澄清

问题描述

我无法理解以下代码输出的原因

    public static void Main()
    {
        var p1 = "txtbox"; 
        CheckMatch(p1);
        p1 = "txtbox_asd";
        CheckMatch(p1);
        p1 = "txtbox_asdf";
        CheckMatch(p1);
        p1 = "txtbox_asd2";
        CheckMatch(p1);
    }

    public static void CheckMatch(string p1)
    {
        var reg = new Regex(@"txtbox");
        if (!reg .IsMatch(p1))
        {
            Console.WriteLine($"{p1} doesn't match");
        }
        else
        {
            Console.WriteLine($"{p1} matches");
        }
    }

所有案例都返回“匹配”,而我只希望第一个案例匹配。有没有办法让它只有第一个案例匹配?

标签: c#regex

解决方案


推荐阅读