2008-08-12 52 views

回答

7
int indexVal = 0; 
Regex re = new Regex(@"Index: (\d*)") 
Match m = re.Match(s) 

if(m.Success) 
    indexVal = int.TryParse(m.Groups[1].toString()); 

可能我的组号错,但你应该能够从这里找到答案。

1

你要利用匹配组,所以像...

Regex MagicRegex = new Regex(RegexExpressionString); 
Match RegexMatch; 
string CapturedResults; 

RegexMatch = MagicRegex.Match(SourceDataString); 
CapturedResults = RegexMatch.Groups[1].Value; 
7

我认为帕特里克保密工作做的 - 我唯一的建议是要记住,命名正则表达式组同时存在,也因此你不要使用数组索引号。

Regex.Match(s, @"Index (?<num>\d*)").Groups["num"].Value 

我找到正则表达式的可读性有点这种方式为好,虽然opinions vary ...

1

这将是

int indexVal = 0; 
Regex re = new Regex(@"Index: (\d*)"); 
Match m = re.Match(s); 

if (m.Success) 
    indexVal = m.Groups[1].Index; 

您也可以命名你组(在这里我ve也跳过了汇编的正则表达式)

int indexVal = 0; 
Match m2 = Regex.Match(s, @"Index: (?<myIndex>\d*)"); 

if (m2.Success) 
    indexVal = m2.Groups["myIndex"].Index; 
0
int indexVal = 0; 
Regex re = new Regex.Match(s, @"(<?=Index:)(\d*)"); 

if(re.Success) 
{ 
    indexVal = Convert.ToInt32(re.Value); 
} 
相关问题