如何在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);
}