题
如何在 C# 中使用正则表达式检索选定的文本?
我正在寻找与此 Perl 代码等效的 C# 代码:
$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.Match(s, @"Index (?<num>\d*)").Groups["num"].Value
不过,我发现正则表达式这样也更具可读性 意见不一...
你会想要利用匹配的组,所以像......
Regex MagicRegex = new Regex(RegexExpressionString);
Match RegexMatch;
string CapturedResults;
RegexMatch = MagicRegex.Match(SourceDataString);
CapturedResults = RegexMatch.Groups[1].Value;
那将是
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)");
Match m = re.Match(s);
if (m.Success)
indexVal = m.Groups[1].Index;
您还可以为您的组命名(这里我也跳过了正则表达式的编译)
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);
}
不隶属于 StackOverflow