在C#普通防爆pression组 [英] Regular Expression Groups in C#

查看:134
本文介绍了在C#普通防爆pression组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承包含以下的正则表达式一个code座,我试图了解它是如何得到它的结果。

I've inherited a code block that contains the following regex and I'm trying to understand how it's getting its results.

var pattern = @"\[(.*?)\]";
var matches = Regex.Matches(user, pattern);
if (matches.Count > 0 && matches[0].Groups.Count > 1)
    ...

对于输入用户==约什·史密斯[JSMITH]

matches.Count == 1
matches[0].Value == "[jsmith]"

...我明白了。但随后

... which I understand. But then:

matches[0].Groups.Count == 2
matches[0].Groups[0].Value == "[jsmith]"
matches[0].Groups[1].Value == "jsmith" <=== how?

看着<一个href=\"http://stackoverflow.com/questions/3320823/whats-the-difference-between-groups-and-captures-in-net-regular-ex$p$pssions\">this从我的理解Groups集合存储整场比赛还有previous匹配问题。但是,上面确实不匹配的正则表达式只为[左方括号] [文] [关闭括号]那么,为什么jsmith的比赛?

Looking at this question from what I understand the Groups collection stores the entire match as well as the previous match. But, doesn't the regexp above match only for [open square bracket] [text] [close square bracket] so why would "jsmith" match?

此外,它是永远的收藏群体将存储恰好2组的情况下:在整场比赛和最后一场比赛

Also, is it always the case the the groups collection will store exactly 2 groups: the entire match and the last match?

推荐答案

()作为一个捕获组。所以比赛阵列的所有比赛中,C#语言字符串中的发现和子阵列具有那些比赛内的捕获组的值。如果你不希望捕捉额外的水平突出部分删除()

The ( ) acts as a capture group. So the matches array has all of matches that C# finds in your string and the sub array has the values of the capture groups inside of those matches. If you didn't want that extra level of capture jut remove the ( ).

这篇关于在C#普通防爆pression组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆