如何在C#中使用Regex检索选定的文本?

时间:2020-03-05 18:39:17  来源:igfitidea点击:

如何在C#中使用Regex检索选定的文本?

我正在寻找与此Perl代码等效的Ccode:

$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = ;}

解决方案

回答

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;

回答

我认为Patrick钉上了这个-我唯一的建议是记住命名的正则表达式组也存在,因此我们不必使用数组索引号。

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

我发现正则表达式也以这种方式更具可读性,尽管意见不尽相同...

回答

那会是

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

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

我们也可以命名组(在这里我也跳过了regexp的编译)

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

if (m2.Success)
    indexVal = m2.Groups["myIndex"].Index;