Replace the last occurrence of a specific sentence in a block of text

My goal is to replace only the last occurrence of %Variable%To_Replace_Line% in a file using regular expressions. For example, with the following text:

- *Page 9:* Can he get the hot pot? *A woman:* Stop! Drop the pot!
- *Page 10:* Dog gets the hot pot!
- *Page 10:* Dog gets the hot pot!

I only need to replace the last occurrence of - *Page 10:* Dog gets the hot pot! with Replacement bla bla bla. So the wanting result would be

- *Page 9:* Can he get the hot pot? *A woman:* Stop! Drop the pot!
- *Page 10:* Dog gets the hot pot!
Replacement bla bla bla

How can I achieve this? I couldn't figure it out with ChatGPT or Perplexity. Can anyone here help?

Here’s a test macro you can try :arrow_down:
replace only the last occurrence of a sentence.kmmacros (5.9 KB)

Macro preview :arrow_down:

With the lines reversed,

for each line,

you can prepend the current line to the (initially empty) output accumulator if the replacement has already been done, or the current line doesn't match the target,

and otherwise, prepend the replacement line.

Last matching line replaced.kmmacros (8.2 KB)

Is this what you want?

* Replace Line.kmmacros (3.2 KB)

3 Likes

Do you need to use a regex? If you can do a straight string search-and-replace, @kcwhat's "Last Match" has you covered.

If you do want to use a regex you'll need to do more work -- your sample string has special regex characters (*) in it, which you'll need to escape. And other potential search strings may have other characters you'd need to check for.

1 Like

A story that is all too familiar. The population dynamics of regular expressions, and the amount of time that they cost the infected hosts, look very much like the dynamics of viral infection.

( Once you have caught the bug, it takes so much practice, over such a long time, just to get past the stage of absolutely massive time-wasting, that you start encouraging others to feed the infection with edible problems :slight_smile: , and thus the contamination spreads ... If they were even Turing-complete, the reward might be greater, and the costs less inordinate ... )

Thank you so much! I had no idea you could choose “All Matches,” “First Match,” or “Last Match” for a search and replace action. That’s amazing!

Thank you @Nige_S ! I didn’t even notice the “Last Match” feature until you mentioned it. :smile:

Thank you, @ComplexPoint ! In other scenarios where the text isn’t too lengthy and there’s no ‘Last Match’ function, this could be a great way to solve the problem. Thank you for your reply!

1 Like