2010/07/27

[C#] Regular Expression 的 Named Group

概念:
使用 (?<GroupName>Regular Expression) 將符合 Regular Expression 的字串放進群組, 並以 GroupName 做索引值來取用.
以下範例來自於 [藍色小鋪]
範例1:
將 [QryGuideIDList:0001+2=g1+n1+g2+n2+g3+n3] 拆成
PGID: 0001
ListSize: 2
GuideID: g1,g2,g3
GuideName: n1,n2,n3

程式碼:
//先將PGID與ListSize取出, g1+n1+g2+n2+g3+n3放至Guide中. 
Regex pattern1 = new Regex(
@"^\[QryGuideIDList:(?<PGID>.*)\+(?<ListSize>.*)\=(?<Guide>.*)\]$"
, RegexOptions.IgnoreCase);
Match match = pattern1.Match("[QryGuideIDList:0001+2=g1+n1+g2+n2+g3+n3]");
Console.WriteLine(match.Groups["PGID"].Value);
Console.WriteLine(match.Groups["ListSize"].Value);
Console.WriteLine(match.Groups["Guide"].Value);

//再將Guide值套用另一個pattern, 用g+n的方式將值分配給GuideID與GuideName
Regex pattern2 = new Regex(
@"(?<GuideID>g\d+)\+(?<GuideName>n\d+)"
, RegexOptions.IgnoreCase);
MatchCollection matchGuides = pattern2.Matches(match.Groups["Guide"].Value);
foreach (Match guide in matchGuides)
{
    Console.WriteLine("GuideID={0}, GuideName={1}"
, guide.Groups["GuideID"].Value, guide.Groups["GuideName"].Value);
}
範例2:
取出關鍵字前後各 10 個字(最多):
string s = "宋胡會可望談兩岸政治定位【吳燕玲╱台北報導】連胡會之後國民黨單獨召開記者會,"
+ "以新聞公報的形式發布五大共識,親民黨中央昨天不願對連胡會發表看法";
Regex pattern2 = new Regex(@"(?.{0,10}連胡會.{0,10})", RegexOptions.IgnoreCase);
MatchCollection matchGuides = pattern2.Matches(s);
foreach (Match guide in matchGuides)
{
    Console.WriteLine("KeyWord={0}", guide.Groups["KeyWord"].Value);
}

沒有留言: