Search code examples
regexnotepad++

How to swap + for - in notepad++ using regular expression


I'm sorry if this has been covered before, I did try to find a previous question covering this but given the subject of the question it's kinda hard to filter through the thousands of answers to other questions.

I have a very large document that contains values denoted by a "+" or a "-". I need to reverse the values in this file.

I know enough to find and replace multiple characters using regex however I don't know enough to search for characters that are used by regex.

I've tried using quotations and even including the | on either side that appear in the file but obviously this is also used in regex.

Is this even possible, how can I get regex to search for "+"?

EDIT: Using normal find and replace is not the solution as this would leave me with all of one character and none of the other but I need to swap them to reverse the value of the whole file.

Onthrax and markalex have already helped me to fix my regex but I'm still open to other solutions.


Solution

  • Replace:

    (\+)|-
    

    ...with:

    (?1-:+)
    

    (\+) matches and captures every + sign whereas - matches, without capturing, every - sign. (?1-:+) means "add - back if group 1 was captured, + otherwise". This effectively swaps the two signs.

    Try it on regex101.com (with minor differences in syntax).

    Alternatively, you can replace:

    1. every + with a temporary sign
    2. every - with +
    3. every temporary sign used in step 1 with -

    This, however, requires the temporary sign we use to not be used in the whole document.