1

Using regular expression match the text exactly after n lines.

In the below example, I want to ensure that request is exactly after 3rd line from id: 1

Example:

signal {
   id: 1
   files: 1.bin
   major: 338013710701
   request {
      reqId: 101
      files: 1.bin
      major: 35723057325
      status: Sent
   }
   response {
      resId: 201
      files: 1.bin
      major: 27151510570
      status: Accepted
   }
}

Note: The value of n will vary based on the input(n may have the value upto than 100). where n is number of lines after which the string is present

I tried with the regular expression /signal\s*{\s*id:\s*1\n[^\n]*\n[^\n]*\s*request/m for the above example since n the value of n is minimal.

Can anyone help in framing the regular expression if n is 100? Thanks in advance.

MIZ
  • 385
  • 1
  • 14

2 Answers2

1

The {100} quantifier indicated that the preceding (\n[^\n]*) should occur exactly 100 times:

/signal\s{\s*id:\s*1(\n[^\n]*){100}request/m

see demo

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
1

Try:

\bid: 1\b(?:.*\R){3}.*request

Set case insensitive and dot does NOT match linebreak

In the above \R is a unicode linebreak. Not supported in earlier versions of Ruby so, if that is an issue, substitute something like \n or whatever linebreak sequence is appropriate for your environment.

Ron Rosenfeld
  • 53,870
  • 7
  • 28
  • 60