Search code examples
regexreplacenotepad++

Use Notepad++ to Capitalize Letters in Snake Case


I'm using Notepad++ to find/replace and can't quite get what I need.

My Current Output is being generated with ^(.+)$ as my Find and ,dim_date[(\1)].alias\((\1)\) as my Replace. It's close, but I can't get the uppercase between the parenthesis as it is in the Desired Output.

If I can alter my find/replace to do it all in one step, that's cool; but I don't mind keeping my first find/replace and then performing another find/replace to get the snake case capitalized. Whatever is easier.

Sample Input:

'business_year'
'business_year_month'
'business_year_quarter'

My Current Output:

,dim_date['business_year'].alias('business_year')
,dim_date['business_year_month'].alias('business_year_month')
,dim_date['business_year_quarter'].alias('business_year_quarter')

Desired Output:

,dim_date['business_year'].alias('Business_Year')
,dim_date['business_year_month'].alias('Business_Year_Month')
,dim_date['business_year_quarter'].alias('Business_Year_Quarter')

Solution

    • Ctrl+H
    • Find what: '([a-z]+)(?:_([a-z]+)(?:_([a-z]+))?)?'
    • Replace with: ,dim_date[$0].alias\('\u$1(?2_\u$2(?3_\u$3))'\)
    • TICK Match case
    • TICK Wrap around
    • SELECT Regular expression
    • UNTICK . matches newline
    • Replace all

    Explanation:

    '               # single quote
    ([a-z]+)        # group 1, 1 or more lowercase
    (?:             # non capture group
        _               # underscore
        ([a-z]+)        # group 2, 1 or more lowercase
        (?:             # non capture group
            _               # underscore
            ([a-z]+)        # group 3, 1 or more lowercase
    *** you can add as many groups as needed
        )?              # end group, optional
    )?              # end group, optional
    '               # single quote
    

    Replacement:

    ,dim_date[      # literally
    $0              # the whole match
    ].alias\('      # lierally
    \u$1            # uppercase the first letter of group 1
    (?2             # if group 2 exists
        _\u$2           # underscore and upper the first letter of group 2
        (?3             # if group 3 exists
            _\u$3           # underscore and upper the first letter of group 3
        )               # endif
    )               # endif
    '\)             # literally
    

    Screenshot (before):

    enter image description here

    Screenshot (after):

    enter image description here