[英]c# RegEx what line is the match on. Linq?
這個應該很簡單,但它難倒我。
我有一個可以匹配的正則表達式。 如果是這樣,我想知道它在哪條線上。 有沒有一種簡單的方法可以用 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
}
您可以逐行匹配:
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}");
}
快跑人,
您可以通過使用 LINQ 結合如下索引來執行此操作:
using System.Linq;
using System.Text.RegularExpressions;
var rx = new Regex(myRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
var docLines = File.ReadAllLines(myDocPath);
var matchLine = docLines.Select((line, index) => new { line, index }).FirstOrDefault(l => rx.IsMatch(l.line));
if(matchLine != null) Console.WriteLine($@"Match line # = {matchLine.index}");
雖然編譯器確實(正如其他人提到的那樣)迭代這些行以完成任務,但我感覺上面是您的想法。
編輯
鑒於您對目標字符串可能跨越多行的評論,我將執行以下操作:
var rx = new Regex(myRegEx, RegexOptions.Compiled | RegexOptions.IgnoreCase);
//Read all text into a variable.
var docLines = File.ReadAllText(myDocPath);
//Check that there is, in fact, a match.
if(!rx.IsMatch(docLines)) return;
//Split your text blob by that match.
var rxSplit = rx.Split(docLines);
//Then count the number of line brakes before the match.
var startOfMatchLine = new Regex(@"(\n|\r\n?)").Matches(rxSplit[0]).Count;
//And print the result.
Console.WriteLine($@"{startOfMatchLine}");
您可以使用match.Value
找到該行,例如:
Regex rx = new Regex("b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
string[] docLines = new[] { "zzazz", "zzbzz", "zzczz", "zzzzz" };
// Find matches
MatchCollection matches = rx.Matches(string.Join(Environment.NewLine, docLines));
if (matches.Count > 0)
{
string loc = matches[0].Value;
//Find the Line
var line = docLines.FirstOrDefault(x => x.Contains(loc));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.