Search code examples
pythonnotepad++

Notepadd++ Python Script: Delete everything between the last 3 " - " if line starts with X


Looking at the end of the line counting the " - " backwards (notice the spaces) and delete the text but only if the line starts with fx TEST.

Before

TESTMouse - Dog - CAT - Fish
Mouse - Dog - CAT - Fish
TESTRat - Whale - Bird - Horse - Snake

After

TESTMouse
Mouse - Dog - CAT - Fish
TESTRat - Whale

This is beyond my ability to write myself and I have not found anything that would work in my searches.


Solution

  • No needs for Notepad++ PythonScript, a simple find and replace is enough:

    • Ctrl+H
    • Find what: ^TEST.*?\K(?: - \w+){3}$
    • Replace with: LEAVE EMPTY
    • TICK Match case
    • TICK Wrap around
    • SELECT Regular expression
    • UNTICK . matches newline
    • Replace all

    Explanation:

    ^           # beginning of line
        TEST        # literally
        .*?         # 0 or more any character, not greedy
        \K          # forget all we have seen until this position
        (?:         # non capture group
            - \w+      # space, hyphen, space, 1 or more word character
        ){3}        # end group, must appear 3 times
    $           # end of line
    

    Replacement:

    Screenshot (before):

    enter image description here

    Screenshot (after):

    enter image description here