首页 > 解决方案 > c# RegEx 匹配在哪一行。林克?

问题描述

这个应该很简单,但它难倒我。

我有一个可以匹配的正则表达式。如果是这样,我想知道它在哪条线上。有没有一种简单的方法可以用 Linq 做到这一点,而不用遍历每一行来计算字符?

  Regex rx = new Regex(myRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
  string[] docLines = File.ReadAllLines(myDocPath);
  // Find matches
  MatchCollection matches = rx.Matches(string.Join(Environment.NewLine, docLines));
  if(matches.Count > 0)
  {
    long loc = matches[0].Index;
    //Find the Line
  }

标签: c#regexlinq

解决方案


您可以逐行匹配:

  Regex rx = new Regex(myRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
  string[] docLines = File.ReadAllLines(myDocPath);
  // Find matches
  for(int x = 0; x < docLines.Length; x++){
    string line = docLines[x];
    if(rx.IsMatch(line))
      Console.Write($"Match on line {x}");
  }

推荐阅读