規則運算式,取出 Group 指定的內容

 從 public int EmployeeID { get; set; }
取出 int 及 EmployeeID 的方式

這篇只講 "搜尋" 的方式

程式

string source = @"
public class Employees
{
    public int EmployeeID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Title { get; set; }
    public string TitleOfCourtesy { get; set; }
    public DateTime? BirthDate { get; set; }
    public DateTime? HireDate { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string HomePhone { get; set; }
    public string Extension { get; set; }
    public byte[] Photo { get; set; }
    public string Notes { get; set; }
    public int? ReportsTo { get; set; }
    public string PhotoPath1 { get; set; }
}
";

string pattern = @"public\s+(.+?)\s+(\w+)\s+\{ get; set; \}";
var _matches = Regex.Matches(source, pattern);
foreach (Match _match in _matches)
{
	Console.WriteLine(_match.Groups[0].Value);
	Console.WriteLine(_match.Groups[1].Value);
	Console.WriteLine(_match.Groups[2].Value);
	Console.WriteLine();
}

pattern 裡面有二組括號
第一組括號代表 Groups[1]
第一組括號代表 Groups[2]
Groups[0],代表符合整個 pattern  的字串

結果

public int EmployeeID { get; set; }
int
EmployeeID

public string LastName { get; set; }
string
LastName

public string FirstName { get; set; }
string
FirstName

public string Title { get; set; }
string
Title

public string TitleOfCourtesy { get; set; }
string
TitleOfCourtesy

public DateTime? BirthDate { get; set; }
DateTime?
BirthDate

public DateTime? HireDate { get; set; }
DateTime?
HireDate

public string Address { get; set; }
string
Address

public string City { get; set; }
string
City

public string Region { get; set; }
string
Region

public string PostalCode { get; set; }
string
PostalCode

public string Country { get; set; }
string
Country

public string HomePhone { get; set; }
string
HomePhone

public string Extension { get; set; }
string
Extension

public byte[] Photo { get; set; }
byte[]
Photo

public string Notes { get; set; }
string
Notes

public int? ReportsTo { get; set; }
int?
ReportsTo

public string PhotoPath1 { get; set; }
string
PhotoPath1