Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text between START & END strings excluding the END string in perl

Tags:

regex

perl

I was going through examples and questions on the web related to finding and replacing a text between two strings (say START and END) using perl. And I was successful in doing that with the provided solutions. In this case my START and END are also inclusive to replacement text. The syntax I used was s/START(.*?)END/replace_text/s to replace multiple lines between START and END but stop replacing when first occurrence of END is hit.

But I would like to know how to replace a text between START and END excluding END like this in perl only.

Before:

START
I am learning patten matching.
I am using perl.
END

After:

Successfully replaced.
END
like image 913
Chris Petrus Avatar asked Jan 28 '26 23:01

Chris Petrus


2 Answers

To perform the check but avoid matching the characters you can use positive look ahead:

s/START.*?(?=END)/replace_text/s
like image 184
Robin Avatar answered Jan 31 '26 20:01

Robin


One solution is to capture the END and use it in the replacement text.

s/START(.*?)(END)/replace_text$2/s
like image 23
AntonH Avatar answered Jan 31 '26 19:01

AntonH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!