Why does this loop through Regex groups print the output twice?

I have written this very straight forward regex code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace RegexTest1
{
    class Program
    {
        static void Main(string[] args)
        {
            string a = "\"foobar123==\"";
            Regex r = new Regex("^\"(.*)\"$");
            Match m = r.Match(a);
            if (m.Success)
            {
                foreach (Group g in m.Groups)
                {
                    Console.WriteLine(g.Index);
                    Console.WriteLine(g.Value);
                }
            }
        }
    }
}

However the output is

0
"foobar123=="
1
foobar123==

I don't understand why does it print twice. why should there be a capture at index 0? when I say in my regex ^\" and I am not using capture for this.

Sorry if this is very basic but I don't write Regex on a daily basis.

According to me, this code should print only once and the index should be 1 and the value should be foobar==

Answers


This happens because group zero is special: it returns the entire match.

From the Regex documentation (emphasis added):

A simple regular expression pattern illustrates how numbered (unnamed) and named groups can be referenced either programmatically or by using regular expression language syntax. The regular expression ((?<One>abc)\d+)?(?<Two>xyz)(.*) produces the following capturing groups by number and by name. The first capturing group (number 0) always refers to the entire pattern.

#      Name              Group
- ---------------- --------------------------------
0 0 (default name) ((?<One>abc)\d+)?(?<Two>xyz)(.*)

1 1 (default name) ((?<One>abc)\d+)

2 2 (default name) (.*)

3 One (?<One>abc)

4 Two (?<Two>xyz)

If you do not want to see it, start the output from the first group.


Need Your Help

Google charts duplicating inexistent rows

charts google-api google-visualization rows

I've a google charts loading data from json but it is duplicatin the rows and i don't know why. (see image)

Using xlrd, how to replace missing/NaN cells

python excel xlrd

I am using python to plot data from excel files. I am having problems with cells which have missing data and are filled with 'NA'.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.