Search code examples
regexnotepad++emeditor

Conditional replace depending on which character is found


This is NOT a duplicate of How to use conditionals when replacing in Notepad++ via regex as I am asking something very specific here which I cannot implement following the info in that question. So kindly allow this question.

I want to replace a range of characters with a corresponding range of characters. So far, I can only do it with multiple operations.

For example, match any word that starts with a capital Latin character in the range [ABEZHIKMNOPTYXZ] and is followed by a Greek lowercase letter [α-ωά-ώ] and replace the character in the first matched group with a similar-looking character but in the Greek range [ΑΒΕΖΗΙΚΜΝΟΡΤΥΧΖ] (note, they look the same but are different characters).

What I came up so far was multiple replacements, ie.

(A)([α-ωά-ώ])
Α\2

(B)([α-ωά-ώ])
Β\2

....

So that for example: Aνθρώπινος would become Ανθρώπινος

Bάτος would become Βάτος

Preferably this should work in EmEditor, Notepad++ being the 2nd option.


Solution

  • Notepad++ supports conditional replacement, you can use it like:

    • Find what: (?:(A)|(B)|(E)|(Z)|(H)|(I)|(K)|(M)|(N)|(O)|(P)|(T)|(Y)|(X)|(Z))(?=[α-ωά-ώ])
    • Replace with: (?{1}Α:(?{2}Β:(?{3}Ε:(?{4}Ζ:)))) add the other Greek letters similarly

    Replacement:

    (?:             # start non capture group
    (?{1}           # if group 1 exists "A"
      Α             # replace with greek letter
      :             # else
      (?{2}         # if group 2 exists "B"
        Β           # replace with greek letter
        :           # else
        (?{3}       # and so on ...
          Ε
          :
          (?{4}
            Ζ
            :
          )
        )
      )
    )
    )               # end non capture group
    (?=             # positive lookahead, make sure we have after:
        [α-ωά-ώ]    # a small greek letter
    )               # end lookahead
    

    I've made a test but for only for 2 letters "A" and "B" and replace them with more visual different letters "X" and "Y" just to show the way it works.

    Screen capture (before):

    enter image description here

    Screen capture (after):

    enter image description here