Regex for nth line in a text file

8k Views Asked by At

I've been trying to get this regex down and searched alot for answers What I need is to get the nth (4th in this example) line from a text file I got this down atm

^(?<=([^\n]*\n){3})[^\n]*\n

But it doesn't seem to work (something about needing fixed length patterns in lookbehind) Is there any way to overcome that obstacle?

Can anyone provide a correction\different regex if needed for this problem?

Thanks

Edit:

I'm trying this regex in PowerGrep and it just doesn't work

P.S: Is there a way of getting nth line in powergrep other than regex?

2

There are 2 best solutions below

7
AudioBubble On BEST ANSWER

Probably need to use a capture buffer.
This regex uses MULTI_LINE mode.
Capture buffer 1 contains the 4th line

 #  (?:^[^\n]*\n){3}([^\n]*)

 (?: ^ [^\n]* \n ){3}
 ( [^\n]* )

Edit: here is the same thing without multi-line mode

 #  ^(?:[^\n]*\n){3}([^\n]*)

 ^ 
 (?: [^\n]* \n ){3}
 ( [^\n]* )
0
user890332 On

Much better just use Regex.Split

Regex.Split(text, "\n", RegexOptions.Multiline)(3)

That will give you the 4th line in a text string.