当谈到.NET的正则表达式语言时,我对"组"和"捕获"之间的区别有点模糊.考虑以下C#代码:
MatchCollection matches = Regex.Matches("{Q}", @"^\{([A-Z])\}$");
Run Code Online (Sandbox Code Playgroud)
我希望这会导致单个捕获字母'Q',但如果我打印返回的属性MatchCollection,我看到:
matches.Count: 1
matches[0].Value: {Q}
matches[0].Captures.Count: 1
matches[0].Captures[0].Value: {Q}
matches[0].Groups.Count: 2
matches[0].Groups[0].Value: {Q}
matches[0].Groups[0].Captures.Count: 1
matches[0].Groups[0].Captures[0].Value: {Q}
matches[0].Groups[1].Value: Q
matches[0].Groups[1].Captures.Count: 1
matches[0].Groups[1].Captures[0].Value: Q
Run Code Online (Sandbox Code Playgroud)
到底发生了什么?我知道整个比赛也有一个捕获,但这些小组是如何进入的?为什么不matches[0].Captures包括字母'Q'的捕获?
我正在尝试使用正则表达式将字符串分成两部分.字符串格式如下:
text to extract<number>
Run Code Online (Sandbox Code Playgroud)
我一直在使用(.*?)<,<(.*?)>哪个工作正常,但在阅读了一点regex之后,我才开始想知道为什么我需要?表达式中的.我通过这个网站找到它们之后才这样做,所以我不确定它们之间的区别.