分组: 一个字符串的模式应该看作一个不同的项。例如:要分别匹配姓和名。
一 简单分组:
1.1 捕获:"()"
概念:括号内的模式是整个模式的一个组,并作为一个组来匹配。
MatchCollection matchesFound;
Regex matchRegex = new Regex( @" ([A-Z]{3})d " );
matchesFound = matchRegex.Matches( " ABC1 DEF2 XY " );
GroupCollection matchGroups;
foreach (Match match in matchesFound)
... {
matchGroups = match.Groups;
Console.WriteLine(matchGroups[1].Value);
}
Regex matchRegex = new Regex( @" ([A-Z]{3})d " );
matchesFound = matchRegex.Matches( " ABC1 DEF2 XY " );
GroupCollection matchGroups;
foreach (Match match in matchesFound)
... {
matchGroups = match.Groups;
Console.WriteLine(matchGroups[1].Value);
}
1.2 非捕获:"(?:)
概念:括号内的模式不是整个模式的一个组,但作为整个模式的一个部分来匹配。
MatchCollection matchesFound;
Regex matchRegex = new Regex( @" (?:d)w " );
matchesFound = matchRegex.Matches( " 1A BB 1 c " );
foreach (Match match in matchesFound)
... {
Console.WriteLine(match.Value);
}
Regex matchRegex = new Regex( @" (?:d)w " );
matchesFound = matchRegex.Matches( " 1A BB 1 c " );
foreach (Match match in matchesFound)
... {
Console.WriteLine(match.Value);
}
1.3 通过名称捕获:(?<name>)
概念:括号内的模式是整个模式的一个组,并且通过尖括号的组名来匹配。
MatchCollection matchesFound;
Regex matchRegex = new Regex( @"/b [A-Z][a-z]+ (?<lastName>[A-Z][a-z]+)/b " );
matchesFound = matchRegex.Matches( " Zhao Rui yan li Gugu Da 123121 sdfd " );
GroupCollection matchGroups;
foreach (Match match in matchesFound)
... {
matchGroups = match.Groups;
Console.WriteLine(matchGroups["lastName"].Value);
}
Regex matchRegex = new Regex( @"/b [A-Z][a-z]+ (?<lastName>[A-Z][a-z]+)/b " );
matchesFound = matchRegex.Matches( " Zhao Rui yan li Gugu Da 123121 sdfd " );
GroupCollection matchGroups;
foreach (Match match in matchesFound)
... {
matchGroups = match.Groups;
Console.WriteLine(matchGroups["lastName"].Value);
}
1.4 比较简单的组
在括号内用"|"(或)来分组匹配的模式。
MatchCollection matchesFound;
Regex matchRegex = new Regex( @" (Mr|Mrs|Miss|Ms|Dr) [A-Z][a-z]* " );
matchesFound = matchRegex.Matches( " Mr Micole love Miss Sara " );
foreach (Match match in matchesFound)
... {
Console.WriteLine(match.Value);
}
Regex matchRegex = new Regex( @" (Mr|Mrs|Miss|Ms|Dr) [A-Z][a-z]* " );
matchesFound = matchRegex.Matches( " Mr Micole love Miss Sara " );
foreach (Match match in matchesFound)
... {
Console.WriteLine(match.Value);
}