0

I'm having trouble understanding the reason for the output of the following code

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

All of the cases are returning 'matches', whereas I am only expecting the first case to match. Is there a way to have it s.t. only the first case matches?

dk123
  • 18,684
  • 20
  • 70
  • 77
  • 2
    If you want full string to mach, then you have to put `^` and `$` to your regex, i.e. `^txtbox$`. Otherwise with `txtbox` regex if your text contains `txtbox`, it will be successfully matched. – Ulugbek Umirov May 05 '19 at 21:12
  • 1
    Additionally to what UlugbekUmirov correctly mentioned you can simplify that to `p1 == "textbox"` in that case. – sticky bit May 05 '19 at 21:20
  • What is the point of using a Regex if you are only looking for a specific string and not for a rule? – Avi Meltser May 05 '19 at 22:23
  • @UlugbekUmirov Thanks, that works. If you could write an answer, I'd be happy to accept. – dk123 May 05 '19 at 22:44
  • @AviMeltser It's because the above is just one simple example. I'd also like proper matches on ex. textbox.*, I just couldn't understand why all cases of textbox_ was matching what I thought should only match if the rule was textbox.* – dk123 May 05 '19 at 22:45

0 Answers0