Nikesh
Nikesh

Reputation: 41

What is simpliest way to get Line number and position no in regex matches charcter?

When I have a match, obtained using the Regex class, how do I find the matching line number and position in that line, of the match, like Notepad++ does?

Example:

void Main()
{
    string _strText = @"Line 1
Line 2
Line 3";
    var re = new Regex("2");
    var m = re.Match(_strText);
    if (m.Success)
    {
        Console.WriteLine(m.Index); // outputs 13
                                    // 13 -> line 2, position 6?
    }
}

Upvotes: 0

Views: 285

Answers (1)

Nikesh
Nikesh

Reputation: 41

get matching line no:

 long lineNumber = _strText.Substring(0, m.Index).LongCount(chr => chr == '\n') + 1;

and get spacific charcter position in this line:

int fis = _strText.LastIndexOf("\n", m.Index);
                    int posi = m.Index - fis;

here posi is the col position this code very helpful for get matching character line no and in this line col no like visual studio editor

Upvotes: 3

Related Questions