[英]Regex - Match versus Groups
预先抱歉,如果将其重复,但是我看不到这些回答了我的问题。
您能帮忙解释一下吗?
仅针对name
的比赛或比赛在哪里举行? 模式[A-Za-z0-9_\\-\\.]+
部分未在方括号中显示,因此我知道它不会是一个组,然后如何捕获name
并将其保留为Match 0
的组成部分?
如果我将字符串t2
替换为name@domain.com alt@yahoo.net
并将模式替换为^([A-Za-z0-9_\\-\\.\\ ]+@(([A-Za-z0-9\\-])+\\.)+([A-Za-z\\-])+)+$
0=com
和Capture 1=net
,类似于Group 2持有domain.
和yahoo.
捕获,为什么? static void Main(string[] args)
{
string t2 = "name@domain.com";
string p2 = @"^[A-Za-z0-9_\-\.\ ]+@(([A-Za-z0-9\-])+\.)+([A-Za-z\-])+$";
MatchCollection matches = Regex.Matches(t2, p2);
GroupCollection gc;
int groupIndex = 0;
int matchIndex = 0;
int captureIndex = 0;
foreach (Match nextMatch in matches)
{
gc = nextMatch.Groups;
Console.WriteLine("Match {0} holds: {1}", matchIndex, nextMatch.Value);
matchIndex++;
foreach (Group g in gc)
{
Console.WriteLine("Group {0} holding: {1}", groupIndex, g.ToString());
groupIndex++;
foreach (Capture capture in g.Captures)
{
Console.WriteLine("\tCapture {0} holds {1}", captureIndex, capture.ToString());
captureIndex++;
}
captureIndex = 0;
}
groupIndex = 0;
}
matchIndex = 0;
}
上面代码的输出:
Match 0 holds: name@domain.com
Group 0 holding: name@domain.com
Capture 0 holds name@domain.com
Group 1 holding: domain.
Capture 0 holds domain.
Group 2 holding: n
Capture 0 holds d
Capture 1 holds o
Capture 2 holds m
Capture 3 holds a
Capture 4 holds i
Capture 5 holds n
Group 3 holding: m
Capture 0 holds c
Capture 1 holds o
Capture 2 holds m
Press any key to continue . . .
如果字符串t2 = "name@domain.com alt@yahoo.net";
输出t2 = "name@domain.com alt@yahoo.net";
和字符串p2 = @"^([A-Za-z0-9_\\-\\.\\ ]+@(([A-Za-z0-9\\-])+\\.)+([A-Za-z\\-])+)+$"
;
Match 0 holds: name@domain.com alt@yahoo.net
Group 0 holding: name@domain.com alt@yahoo.net
Capture 0 holds name@domain.com alt@yahoo.net
Group 1 holding: alt@yahoo.net
Capture 0 holds name@domain.com
Capture 1 holds alt@yahoo.net
Group 2 holding: yahoo.
Capture 0 holds domain.
Capture 1 holds yahoo.
Group 3 holding: o
Capture 0 holds d
Capture 1 holds o
Capture 2 holds m
Capture 3 holds a
Capture 4 holds i
Capture 5 holds n
Capture 6 holds y
Capture 7 holds a
Capture 8 holds h
Capture 9 holds o
Capture 10 holds o
Group 4 holding: t
Capture 0 holds c
Capture 1 holds o
Capture 2 holds m
Capture 3 holds n
Capture 4 holds e
Capture 5 holds t
Press any key to continue . . .
Match
涵盖整个正则表达式的匹配。 正则表达式可以应用于给定的字符串。
Group
是该Match
和Capture
的一部分(如果您指定了多个出现的组,例如(someRegex)+),则是该Group
所有Capture
。 尝试将([A-Za-z\\-])+
更改为([A-Za-z\\-]+)
,看看有什么不同!
例子:
\\w*(123)\\w*
on "asdsa123asdf"
\\w*([123])+\\w*
在"asdsa123asdf"
有多个站点可以测试和显示您的正则表达式的详细信息,即https://regexr.com或https://regex101.com
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.