最大的網站源碼資源下載站,
正則表達式中的組是很重要的一個概念,它是我們通向高級正則應用的的橋梁。
組的概念
一個正則表達式匹配結果可以分成多個部分,這就是組(group)的目的。能夠靈活的使用組后,你會發現regex真是很方便,也很強大。
先舉個例子
public static void main()
{
string s = "2005-2-21";
regex reg = new regex(@"(?<y>/d{4})-(?<m>/d{1,2})-(?<d>/d{1,2})",regexoptions.compiled);
match match = reg.match(s);
int year = int.parse(match.groups["y"].value);
int month = int.parse(match.groups["m"].value);
int day = int .parse(match.groups["d"].value);
datetime time = new datetime(year,month,day);
console.writeline(time);
console.readline();
}
以上的例子通過組來實現分析一個字符串,并把其轉化為一個datetime實例,當然,這個功能用datetime.parse方法就能很方便的實現。
在這個例子中,我把一次match結果用(?<name>)的方式分成三個組"y","m","d"分別代表年、月、日。
現在我們已經有了組的概念了,再來看如何分組,很簡單的,除了上在的辦法,我們可以用一對括號就定義出一個組,比如上例可以改成:
public static void main()
{
string s = "2005-2-21";
regex reg = new regex(@"(/d{4})-(/d{1,2})-(/d{1,2})",regexoptions.compiled);
match match = reg.match(s);
int year = int.parse(match.groups[1].value);
int month = int.parse(match.groups[2].value);
int day = int .parse(match.groups[3].value);
datetime time = new datetime(year,month,day);
console.writeline(time);
console.readline();
}
從上例可以看出,第一個括號對包涵的組被自動編號為1,后面的括號依次編號為2、3……
public static void main()
{
string s = "2005-2-21";
regex reg = new regex(@"(?<2>/d{4})-(?<1>/d{1,2})-(?<3>/d{1,2})",regexoptions.compiled);
match match = reg.match(s);
int year = int.parse(match.groups[2].value);
int month = int.parse(match.groups[1].value);
int day = int .parse(match.groups[3].value);
datetime time = new datetime(year,month,day);
console.writeline(time);
console.readline();
}
再看上例,我們用(?<數字>)的方式手工給每個括號對的組編號,(注意我定義1和2的位置時不是從左到右定義的)
通過以上三例,我們知道了給regex定義group的三種辦法以及相應的引用組匹配結果的方式。
然后,關于組定義,還有兩點請注意:
1、因為括號用于定義組了,所以如果要匹配"("和")",請使用"/("和"/)"(關于所有特殊字符的定義,請查看相關regex expression幫助文檔)。
2、如果定義regex時,使用了explicitcapture選項,則第二個例子不會成功,因為此選項要求顯式定義了編號或名字的組才捕獲并保存結果,如果你沒有定義explicitcapture選項,而有時又定義了類式于(a|b)這樣的部分在表達式,而這個(a|b)你又并不想捕獲結果,那么可以使用“不捕獲的組”語法,即定義成(?:)的方式,針對于(a|b),你可以這樣來定義以達到不捕獲并保存它到group集合中的目的--(?:a|b)。