Search code examples
javascriptregexvisual-studio-codecode-snippets

How to use Regex to 'capitalize and replace' in Visual Studio Code's snippets?


I want to create a snippet on Visual Studio Code .

I tried to manually join the Regex but it never worked like my expect:

input: idss-static-frame.spec

expected result: IdssStaticFrame

my Regex: ${TM_FILENAME_BASE/((\\w+(?=\\-))*(\\w+(?=\\.))*)((\\-)*)/${1:/capitalize}/g}

actual result: IdssStaticFrame.spec

I couldn't remove .spec string


Solution

  • For this kind of filenames, you may use

    "${TM_FILENAME_BASE/(\\w+)(?:-|\\.\\w+$)/${1:/capitalize}/g}",
    

    See the regex demo

    Details

    • (\w+) - Group 1: one or more word chars
    • (?:-|\.\w+$) - - or . + 1 or more word chars at the end of string.

    You may use

    "${TM_FILENAME_BASE/([^-]+)(?:-|\\.\\w+$)/${1:/capitalize}/g}",
    

    To match file names that contain chars other than just word chars as [^-]+ matches 1 or more chars other than -.