如何在C#中使用正则表达式检索选定的文本?如何使用C#中的正则表达式检索选定的文本?
我找的C#代码,相当于这个Perl代码:
$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
如何在C#中使用正则表达式检索选定的文本?如何使用C#中的正则表达式检索选定的文本?
我找的C#代码,相当于这个Perl代码:
$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)
if(m.Success)
indexVal = int.TryParse(m.Groups[1].toString());
可能我的组号错,但你应该能够从这里找到答案。
你要利用匹配组,所以像...
Regex MagicRegex = new Regex(RegexExpressionString);
Match RegexMatch;
string CapturedResults;
RegexMatch = MagicRegex.Match(SourceDataString);
CapturedResults = RegexMatch.Groups[1].Value;
我认为帕特里克保密工作做的 - 我唯一的建议是要记住,命名正则表达式组同时存在,也因此你不要有使用数组索引号。
Regex.Match(s, @"Index (?<num>\d*)").Groups["num"].Value
我找到正则表达式的可读性有点这种方式为好,虽然opinions vary ...
这将是
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;
int indexVal = 0;
Regex re = new Regex.Match(s, @"(<?=Index:)(\d*)");
if(re.Success)
{
indexVal = Convert.ToInt32(re.Value);
}