[英]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.