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);
realidad no va a funcionar si el aguja cruza una línea, pero eso es porque la expresión regular no reconoce eso.
Editar tal vez usted puede reemplazar las líneas de fondo en el texto con espacios y aplicar la expresión regular allí, este código todavía iba a funcionar y si la aguja cae sobre una línea que todavía se encuentran:
Regex.Matches(haystack.Replace(Environment.NewLine, " "), needle)
creo que una opción mucho más atractiva sería utilizar un 'StringReader' para el pajar y usar' ReadLine() 'para leer las líneas en lugar de dividir esa manera. –
cierto - Yo había asumido que 'haystack' ya está cargado en la memoria, si no es así, para los archivos más largos absolutamente' File.ReadLines() 'sería preferido – BrokenGlass