Search code examples
regex-group

How to group second word of any line and replace them separately


how can I replace first word of each line which starts with ("w" "b) to ("white" "black") and the second words all that has "K" "Q" "B" to "king""Queen""Bishop"

For example below is my text

wk

wQ

wB

wR

wN

wP

bk

bQ

bB

bR

bN

bP

Output should be

White King

White Queen

White Bishop

White Rook

White Knight

White Pawn

&

Black King

Black Queen

Black Bishop

Black Rook

Black Knight

Black Pawn

Until end.

I believe it'l be possible,

Any help will be appreciated.


Solution

  • This can be done with Notepad++, using conditional replacement:

    • Ctrl+H
    • Find what: (?:(w)|(b))(?:(k)|(q)|(b)|(r)|(n)|(p))
    • Replace with: (?1White:Black) (?3King:(?4Queen:(?5Bishop:(?6Rook:(?7Knight:Pawn)))))
    • UNCHECK Match case
    • CHECK Wrap around
    • CHECK Regular expression
    • Replace all

    Explanation:

    (?:         # non capture group
        (w)         # group 1, letter w
      |           # OR
        (b)         # group 2, letter b
    )           # end group
    (?:         # non capture group
        (k)         # group 3, letter k
      |           # OR
        (q)         # group 3, letter q
      |           # OR
        (b)         # group 3, letter b
      |           # OR
        (r)         # group 3, letter r
      |           # OR
        (n)         # group 3, letter n
      |           # OR
        (p)         # group 3, letter p
    )           # end group
    

    Replacement:

    (?1         # if group 1 exists (i.e. letter w),
      White       # put the word White
    :           # else
      Black       # Black
    )
     
    (?3         # if group 3 exists (letter k)
      King        # then King
    :           # else
      (?4         # if group 4 exists (letter q)
        Queen       # then Queen
      :           # else
        (?5         # if group 5 exists
          Bishop      ### and so on...
        :
          (?6
            Rook
          :
            (?7
              Knight
            :
              Pawn
            )
          )
        )
      )
    )
    

    Screenshot (before):

    enter image description here

    Screenshot (after):

    enter image description here