0

I am new to Regex. I am trying to get multiple lines after a string match. Somehow I able to do it, but I feel like that is not the best way. The following code produces a list of a tuple of the next 10 lines and the tenth line.

re.findall(r'(Input orientation(.+\n){10})',f)
  1. Would you please explain how it happened and how can I get a list of matched line and next n lines.
  2. Is there have any way to print m-th to (m+n)th line after matching a string? eg. print 5th to 10th line after matching the string "Input orientation"

I am looking for a regex solution only.

Thanks much

  • What you are asking for is repeated capturing group. With `re`, it is not possible. With PyPi regex, kind of possible, but you still need some code to get the stack of Group 2 captures (if you use your regex). – Wiktor Stribiżew Apr 28 '20 at 20:09
  • 1
    I'm not certain I understand your question, but you may be able to use a regular expression similar to `^.*\bdog and gorilla\b.*\r?\n(?:.*\r?\n){2}((?:.*\r?\n){3})`. This searches for a line containing the string `dog and gorilla` (surrounded by word breaks). If the line is found is skips the next 2 lines and captures the next 3 in capture group 1. [Demo](https://regex101.com/r/Wavohn/2/). – Cary Swoveland Apr 28 '20 at 21:13
  • Excellent, you got my question and it works. Another quick query is, if I do f=open('f.com','r'); re.findall(r'restring',f.readliens()), it producing the result in first run and return nothing in rerunning of re.findall(r'restring',f.readliens()). But if I use f=open('f.com','r').readlines(), then re.findall works in every execution, do you know why? – Jabed A. Mohammed May 04 '20 at 16:42

0 Answers0