c# - 为什么这个通过 Regex 组循环打印输出两次?

标签 c# regex

我写了这个非常直接的正则表达式代码

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

但是输出是

0
"foobar123=="
1
foobar123==

我不明白为什么它会打印两次。为什么要在索引 0 处进行捕获?当我在我的正则表达式中说 ^\" 而我没有为此使用捕获时。

抱歉,如果这是非常基础的,但我不是每天都写正则表达式。

根据我的说法,这段代码应该只打印一次,索引应该是 1,值应该是 foobar==

最佳答案

发生这种情况是因为第 0 组很特殊:它返回整个匹配项。

来自Regex documentation (强调):

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)

不想看就从第一组开始输出

关于c# - 为什么这个通过 Regex 组循环打印输出两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26002882/

相关文章:

regex - grepl重复上界和加号

regex - HTACCESS重写: Ignore another rewrite rule

c# - 如何使用具有 "greedy"构造函数的 Scan 将 StructureMap 与通用未封闭类型一起使用

c# - "service"和 "component"有什么区别?

c# - 为什么这两个对象没有链接?

javascript - 使用 javascript 在 Mapbox 上使用加载的 geojson 生成器

c# - 正则表达式C#-匹配任何YouTube.com URI

Java 匹配器不工作

c# - 通过 navigation 属性动态 Where 过滤

c# - 使用 Newtonsoft 简化对象的反序列化