我写了这个非常直接的正则表达式代码
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/