Search code examples
regexnotepad++

Using regex to duplicate a selection and replacing some characters


Probably a terrible title.

I am trying to take the following:

Joe Dane
Bob Sagget
Whitney Houston
Some
Other
Test

And trying to produce:

JOE_DANE("Joe Dane"),
BOB_SAGGET("Bob Sagget"),
WHITNEY_HOUSTON("Whitney Houston"),
SOME("Some"),
OTHER("Other"),
TEST("Test"),

I'm using Notepad++ and am close but not good enough at regex to figure out the remaining expression. So far, this is what I have:

Find what: (^.*)
Replace with: \1 \(\"\1\"\),
Produces: Joe Dane("Joe Dane"),

I've tried replacing with: \U$1 \(\"\1\"\), but this also impacts the second instance of \1 with upper case. It also does not replace the whitespace with an underscore _.


Solution

  • This can be done in a single step.


    If you don't have more than 2 words in a line:

    • Ctrl+H
    • Find what: ^(\S+)(?: (\S+))?$
    • Replace with: \U$1(?2_$2)\E\("$0"\),
    • CHECK Wrap around
    • CHECK Regular expression
    • Replace all

    Explanation:

    ^               # beginning of line
    (\S+)           # group 1, 1 or more non space
    (?: (\S+))?     # non capture group, a space, group 2, 1 or more non space, optional
    $
    

    Replacement:

    \U          # uppercased
    $1          # group 1
    (?2_$2)     # if group 2 exists, add and underscore before
    \E          # end uppercase
    \("$0"\),   # the whole match with parens and quote
    

    Screenshot (after):

    enter image description here


    If you have more than 2 words (up to 5), use:

    • Find ^(\S+)(?: (\S+))?(?: (\S+))?(?: (\S+))?(?: (\S+))?

    • Replace: \U$1(?2_$2)(?3_$3)(?4_$4)(?5_$5)\E\("$0"\),

    I you have more thans five word, add as many (?: (\S+))? as needed.