Home > Mobile >  regex find first occurance beginning from end of the line
regex find first occurance beginning from end of the line

Time:09-10

I have this string

test = "total abc total foo total anything here total\ntotal total\ntotal\nstart\notal abc total foo total anything here total\notal abc total foo total anything here total\nstart\notal abc total foo total anything here total\n"

How would I go on about matching from the last occurance of start to the end of the line? I tried to do this with a negative lookahead but I would always get the first occurance: (?!$)\\nstart[\s\S]*?$ Expecting match to be characters: 164-219

CodePudding user response:

You can use

(?ms)^start$(?!.*^start$).*

See the regex demo.

Details:

  • (?ms) - the . matches newlines now and the ^ / $ anchors now match start/end of any line respectively
  • ^ - start of a line
  • start - a fixed word
  • $ - end of a line
  • (?!.*^start$) - a negative lookahead that fails the match if there are any zero or more chars as many as possible followed with start as a whole line
  • .* - the rest of the string.
  • Related