简体   繁体   中英

How do I replace every odd occurrence of a substring with regex in Notepad++?

I would like to change the following

<evenInstance><evenInstance><evenInstance><evenInstance><evenInstance>

to

<oddInstance><evenInstance><oddInstance><evenInstance><oddInstance>

I have gotten the following

<oddInstance><oddInstance><oddInstance><oddInstance><oddInstance><oddInstance>

to be

<oddInstance><evenInstance><oddInstance><evenInstance><oddInstance><evenInstance>

with the regex:

(odd(?:(?!odd).)*)odd((?:(?!odd).)*)

and the substitution:

\1even\2

But I don't know how to do it for odd occurrences. Any help is greatly appreciated.

The first pattern might be shortened to

odd\Kodd(?=(?:oddodd)*$)

Replace with even

Regex demo

Result

oddevenoddevenoddeven

For the second pattern you might use:

even(?=(?:eveneven)*$)

Replace with odd

Regex demo

Result

oddevenoddevenodd

This is the fastest way to do it.
Uses the \\G construct.

(?s)(?:even|(?!^)\\G.*?even.*?\\Keven)

https://regex101.com/r/8BlRJx/1

Formatted

 (?s)
 (?:
      even
   |  
      (?! ^ )
      \G 
      .*? even .*? \K even
 )

Benchmark

Regex1:   (?:even|(?!^)\G.*?even.*?\Keven)
Completed iterations:   3  /  3     ( x 1000 )
Matches found per iteration:   186
Elapsed Time:    1.02 s,   1023.95 ms,   1023953 µs
Matches per sec:   544,946

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM