TAGS :Viewed: 9 - Published at: a few seconds ago

[ Match text(a..b) from the last occurrence of a word(a) till first occurrence of another word(b) ]

Using regular expression on the following input:

Input

response {
   id: 1
   files: 1.bin
   major: 338013710701
   status: Received
}
response {
   id: 1
   files: 1.bin
   major: 35723057325
   status: Valid
}
response {
   id: 1
   files: 1.bin
   major: 27151510570
   status: Accepted
}

I am expecting the matched output:

Expected Output

response {
   id: 1
   files: 1.bin
   major: 27151510570
   status: Accepted

where id: 1 is mandatory for a match. I tried to do it with the following regular expression:

/response {\n {3}id: 1.*?status: Accepted/m

and it selects from the first response till status: Accepted. Can anyone help in framing the right regular expression to match the expected output?

Answer 1


You could try the below regex to match the response block which contains the string status: Accepted,

/response\s*\{\n[^\n]*\n[^\n]*\n[^\n]*\n\s*status: Accepted/m

DEMO

Explanation:

  • response Matches a literal string response.
  • \s* Zeror or more spaces.
  • { A literal { symbol.
  • \n Matches a newline character.
  • [^\n]* Matches anycharacter not of newline zero or more times.
  • \n Matches a newline character.
  • [^\n]* Matches anycharacter not of newline zero or more times.
  • \n\s* A newline and zero or more spaces.
  • status: Accepted Matches the string status: Accepted

Update:

You could use this regex also,

/response {[\s\n\w\.:]*id:\s*1[\s\n\w\.:]*status: Accepted/m

DEMO

Answer 2


use this :

/(.*(response.*?status: Accepted))/s

you will get it in the second backreference

\2 or $2

demo here: http://regex101.com/r/aO2qD8/1