regexnotepad++

Regular expression to replace all occurences of a substring that's not preceeded by another substring


This might have been answered before, however I did not find an answer I could make work. I looked at these without success:

Regular expression to match a line that doesn't contain a word

Regex negative lookahead ignore section of code

I'm trying to use Notepad++ v8.8.1 (64bit) to replace all occurences of a substring save when the substring occurs with another specific substring preceeding it.

The substring to be replaced (Find what: in Npp):

</span><span class="

The substring with the other one in front making it to be ignored:

line-count-display">5</span><span class="

Multiple occurences of both substrings can occur on the same line.

Replace with substring:

</span>❤️<span class="

Testing sample:

good, </span> </span><span class="do capture"
<span class="line-count-display">5</span><span class="do Not capture" good, </span> </span><span class="do capture"
</span> good</span><span class="do capture"

In the testing sample, the output should be:

good, </span> </span>❤️<span class="do capture"
<span class="line-count-display">5</span><span class="do Not capture" good, </span> </span>❤️<span class="do capture"
</span> good</span>❤️<span class="do capture"

I tried this regex which does not work (it does not ignore the 2nd occurence):

((?!line-count-display>\d+))([ ])*</span>([ ])*<span class="

Wrong output:

good, </span></span>❤️<span class="do capture"
<span class="line-count-display">5</span>❤️<span class="do Not capture" good, </span></span>❤️<span class="do capture"
</span> good</span>❤️<span class="do capture" 

Solution

  • You can use the (*SKIP)(*FAIL) PCRE control verbs to find the matching text that is desired to
    skip, then the verbs skip it (moves the current position just past this) then continues on to find the good matching text.

    line-count-display">5</span><span class="(*SKIP)(*FAIL)|(</span>)(<span class=")
    

    replace $1❤️$2

    https://regex101.com/r/vzQTqq/1