Santhosh
Santhosh

Reputation: 11788

regex how to find and replace at multiple instance along multi line search

I have the following text:

vyāsa-prasādāc chrutavānZKL
etad guhyam ahaṁ paramZKL
yogaṁ yogeśvarāt kṛṣṇātZKL
sākṣāt kathayataḥ svayamPXY

rājan saṁsmṛtya saṁsmṛtyaZKL
saṁvādam imam adbhutamZKL
keśavārjunayoḥ puṇyaṁZKL
hṛṣyāmi ca muhur muhuḥPXY

tac ca saṁsmṛtya saṁsmṛtyaZKL
rūpam aty-adbhutaṁ hareḥZKL
vismayo me mahān rājanZKL
hṛṣyāmi ca punaḥ punaḥPXY

yatra yogeśvaraḥ kṛṣṇoZKL
yatra pārtho dhanur-dharaḥZKL
tatra śrīr vijayo bhūtirZKL
dhruvā nītir matir mamaPXY

Now i want:

vyāsa-prasādāc chrutavānZKL
etad guhyam ahaṁ paramZKL
yogaṁ yogeśvarāt kṛṣṇāt sākṣāt kathayataḥ svayamPXY

rājan saṁsmṛtya saṁsmṛtyaZKL
saṁvādam imam adbhutamZKL
keśavārjunayoḥ puṇyaṁ hṛṣyāmi ca muhur muhuḥPXY

tac ca saṁsmṛtya saṁsmṛtyaZKL
rūpam aty-adbhutaṁ hareḥZKL
vismayo me mahān rājan hṛṣyāmi ca punaḥ punaḥPXY

yatra yogeśvaraḥ kṛṣṇoZKL
yatra pārtho dhanur-dharaḥZKL
tatra śrīr vijayo bhūtir dhruvā nītir matir mamaPXY

I want to merge the last two lines in each stanza.

I am trying in sublime text:

find: (?s)ZKL\n((?!.*ZKL).*PXY)
replace:  \1

(?s)  for multi line search
ZKL\n is ZKL and new line
((?!.*ZKL)  to search from ZKL which is before PXY otherwse there are many ZKL
.*PXY everything till PXY

the above will only replace the last instance. How to see that all four instances in four stanzas are replaced.

i have lot off such stanzas

Upvotes: 0

Views: 43

Answers (3)

Pushpesh Kumar Rajwanshi
Pushpesh Kumar Rajwanshi

Reputation: 18357

This regex seems to work PCRE. I am not sure about sublimetext3, can you try this regex?

ZKL\n(?=.*\n\n)

and replace it with just a single space.

Note: I have inserted two new lines after the last paragraph, so that the regex works for last paragraph as well.

Check here

Edit: In case you want to further combine PXY line with two lines above it, you can use ZKL\n and replace it with space.

But in case you want to combine all four lines into one whist removing ZKL and PXY at the end, you can use this regex,

(ZKL|PXY(\n))\n

and remove it with a \2\2

Demo

Upvotes: 0

Poul Bak
Poul Bak

Reputation: 10929

This regex should do the job:

(.+ZKL\n.+ZKL\n.+ZKL)\n(.+PXY)

The regex matches any number of any char up to 'ZKL\n'. This is repeated three times and is stored in Group 1.

Then it matches any number of any char up to 'PXY' This is stored in Group 2.

Now you replace with:

$1$2 or in some languages: \1\2

That will join the last two lines.

You should set the global flag.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271420

You can try this:

ZKL\n(?=.*PXY\n\n)

It matches ZKL followed by a new line, then checks if there are a bunch of non-new-line characters followed by PXY followed by 2 new lines after that.

You can replace it with a space.

Note that for this to work for the last stanza, you need to have at least two new lines at the end of the file.

Demo

Upvotes: 1

Related Questions