Why does .NET Regex return different results with alternation?

20 views Asked by At

I tested this piece of code in .NET Framework 4.7.2:

using System;
using System.Text.RegularExpressions;
                    
public class Program
{
    public static void Main()
    {
        Regex r;

        r = new Regex("^\\.vs$");
        ShowMatch(r, ".vs");
        ShowMatch(r, ".vsa");
        ShowMatch(r, "avs");
        ShowMatch(r, "c.vs");
        
        Console.WriteLine();

        r = new Regex("^bin|obj|\\.vs$");
        ShowMatch(r, "bin");
        ShowMatch(r, "s.bin");
        ShowMatch(r, "obj");
        ShowMatch(r, ".vs");
        ShowMatch(r, ".vsa");
        ShowMatch(r, "avs");
        ShowMatch(r, "c.vs");
    }
    
    public static void ShowMatch(Regex r, string input)
    {
        bool b = r.IsMatch(input);
        Console.WriteLine("Pattern: {0}  Input: {1,-10}  IsMatch: {2}", r, input, b);
    }
}

I got this output:

Pattern: ^\.vs$  Input: .vs         IsMatch: True
Pattern: ^\.vs$  Input: .vsa        IsMatch: False
Pattern: ^\.vs$  Input: avs         IsMatch: False
Pattern: ^\.vs$  Input: c.vs        IsMatch: False

Pattern: ^bin|obj|\.vs$  Input: bin         IsMatch: True
Pattern: ^bin|obj|\.vs$  Input: s.bin       IsMatch: False
Pattern: ^bin|obj|\.vs$  Input: obj         IsMatch: True
Pattern: ^bin|obj|\.vs$  Input: .vs         IsMatch: True
Pattern: ^bin|obj|\.vs$  Input: .vsa        IsMatch: False
Pattern: ^bin|obj|\.vs$  Input: avs         IsMatch: False
Pattern: ^bin|obj|\.vs$  Input: c.vs        IsMatch: True

I don't understand why "c.vs" with the alternation pattern (^bin|obj|.vs$) is considered as a match while the same input with the simple pattern (^.vs$) is not (expected behavior).

0

There are 0 answers