Replace a string when two strings exist in one regex in Perl -


given following input

$ cat pre stuff macro1 stuff macro2 stuff macro2 stuff macro1 stuff macro2 stuff 

i want replace macro2 (with macro3) if macro1 exists. so:

$ perl -ne '/(?=.*macro1).*macro2/ ? print s/macro2/macro3/gr : print' pre stuff macro1 stuff macro3 stuff macro3 stuff macro1 stuff macro2 stuff 

(i imagine .*macro2 part of expression unnecessary, think it) edit. less stupid version of above based on feedback far:

$ perl -ne '/macro1/ ? print s/macro2/macro3/gr : print' pre 

what trying figure out how regex. here 1 attempt:

$ perl -ne 'print s/(?=.*macro1)(?=.*macro2)macro2/macro3/gr' pre stuff macro1 stuff macro2 stuff macro3 stuff macro1 stuff macro2 stuff 

i think having fundamental confusion how lookahead operator can both "anchor" , "non-consuming" @ same time. if think ?= anchor, makes sense me above doesn't work. seem contradict "non-consuming".

can define meant non-consuming , show me regex produce desired results?

first, let's actual solution out there:

perl -pe's/macro2/macro3/g if /macro1/' 

now, let's @ peculiar request. single substitution, following:

perl -pe's/macro2(?:(?<=macro1.*)|(?=.*macro1))/macro3/g' 

ignoring fact doesn't work because variable-width lookbehinds aren't supported, incredibly inefficient. while time required first solution presented bound factor of size of file, time required solution bound factor of size of file times factor of number of instances of macro2!


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -