Get line number for matched template

I use this code to check if a line exists in a text file that I loaded into memory

foreach (Match m in Regex.Matches(haystack, needle)) richTextBox1.Text += "\nFound @ " + m.Index; 

The regular expression returns the positions at which the match occurred, but I want to know the line number?

+6
source share
3 answers

A better solution would be to call a method that gets the line number only if it matches. Thus, performance is not heavily dependent on checking multiple files, and regex with \n will work. Found this method somewhere in stackoverflow:

  public int LineFromPos(string S, int Pos) { int Res = 1; for (int i = 0; i <= Pos - 1; i++) if (S[i] == '\n') Res++; return Res; } 
+5
source

You can first split the text into lines and apply your RegEx to each line - of course, this does not work if the needle contains NewLine:

 var lines = haystack.Split(new[] { Environment.NewLine }, StringSplitOptions.None); for(int i=0; i <lines.Length; i++) { foreach (Match m in Regex.Matches(lines[i], needle)) richTextBox1.Text += string.Format("\nFound @ line {0}", i+1) } 
+5
source
  foreach (Match m in Regex.Matches(haystack, needle)) { int startLine = 1, endLine = 1; // You could make it to return false if this fails. // But lets assume the index is within text bounds. if (m.Index < haystack.Length) { for (int i = 0; i <= m.Index; i++) if (Environment.NewLine.Equals(haystack[i])) startLine++; endLine = startLine; for (int i = m.Index; i <= (m.Index + needle.Length); i++) if (Environment.NewLine.Equals(haystack[i])) endLine++; } richTextBox1.Text += string.Format( "\nFound @ {0} Line {1} to {2}", m.Index, startLine, endLine); 

Actually does not work if the needle crosses the line, but this is because the regular expression does not recognize it.

Change, maybe you can replace the end lines in the text with spaces and apply a regular expression there, this code will still work, and if the needle goes down on the line, it will still be found:

 Regex.Matches(haystack.Replace(Environment.NewLine, " "), needle) 
0
source

Source: https://habr.com/ru/post/903559/


All Articles