Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain the line number for matched pattern

Tags:

c#

regex

I use this code to check if a string exist in a text file that I loaded into memory

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

The regex returns the positions where a match occurred but I want to know the line number?

like image 595
Nenad Avatar asked Dec 11 '11 22:12

Nenad


2 Answers

The best solution would be to call a method that gets the line number only if a match occurs. This way the performance is not much affected if multiple files were checked and the regexp with \n will work. Found this method somewhere on stackoverflow:

    public int LineFromPos(string input, int indexPosition)
    {
        int lineNumber = 1;
        for (int i = 0; i < indexPosition; i++)
        {
            if (input[i] == '\n') lineNumber++;
        }
        return lineNumber;
    }
like image 145
Nenad Avatar answered Sep 21 '22 20:09

Nenad


To do this I did the following...

  • Read file contents into buffer
  • Use regex to match all carriage returns in the file and note there index in a list of carriage returns

    private static List<CarriageReturn> _GetCarriageReturns( string data )
    {
        var carriageReturns = new List<CarriageReturn>();
    
        var carriageReturnRegex = new Regex( @"(?:([\n]+?))", RegexOptions.IgnoreCase | RegexOptions.Singleline );
        var carriageReturnMatches = carriageReturnRegex.Matches( data );
        if( carriageReturnMatches.Count > 0 )
        {
            carriageReturns.AddRange( carriageReturnMatches.Cast<Match>().Select( match => new CarriageReturn
            {
                Index = match.Groups[1].Index,
            } ).ToList() );
        }
    
        return carriageReturns;
    }
    
  • Use my regex on the file and for every match do something like this LineNumber = carriageReturns.Count( ret => ret.Index < match.Groups[1].Index ) + 1

So basically I count the carriage returns occurring before my match and add 1

like image 27
theDoke Avatar answered Sep 18 '22 20:09

theDoke