4

my filename is

some-fancy-ui.component.html

I want to use a vscode snippet to transform it to

SOME_FANCY_UI

So basically

  1. apply upcase to each character
  2. Replace all - with _
  3. Remove .component.html

Currently I have

'${TM_FILENAME/(.)(-)(.)/${1:/upcase}${2:/_}${3:/upcase}/g}'

which gives me this

'SETUP-PRINTER-SERVER-LIST.COMPONENT.HTML'

The docs doesn't explain how to apply replace in combination with their transforms on regex groups.

Han Che
  • 8,239
  • 19
  • 70
  • 116

2 Answers2

11

If the chunks you need to upper are separated with - or . you may use

"Filename to UPPER_SNAKE_CASE": {
    "prefix": "usc_",
    "body": [
        "${TM_FILENAME/\\.component\\.html$|(^|[-.])([^-.]+)/${1:+_}${2:/upcase}/g}"
    ],
    "description": "Convert filename to UPPER_SNAKE_CASE dropping .component.html at the end"
}

You may check the regex workings here.

  • \.component\.html$ - matches .component.html at the end of the string
  • | - or
  • (^|[-.]) capture start of string or - / . into Group 1
  • ([^-.]+) capture any 1+ chars other than - and . into Group 2.

The ${1:+_}${2:/upcase} replacement means:

  • ${1:+ - if Group 1 is not empty,
  • _ - replace with _
  • } - end of the first group handling
  • ${2:/upcase} - put the uppered Group 2 value back.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Here is a pretty simple alternation regex:

"upcaseSnake": {
  "prefix": "rf1",
  "body": [
    "${TM_FILENAME_BASE/(\\..*)|(-)|(.)/${2:+_}${3:/upcase}/g}",

    "${TM_FILENAME/(\\..*)|(-)|(.)/${2:+_}${3:/upcase}/g}"
  ],
  "description": "upcase and snake the filename"
},

Either version works.

(\\..*)|(-)|(.) alternation of three capture groups is conceptually simple. The order of the groups is important, and it is also what makes the regex so simple.

(\\..*) everything after and including the first dot . in the filename goes into group 1 which will not be used in the transform.

(-) group 2, if there is a group 2, replace it with an underscore ${2:+_}.

(.) group 3, all other characters go into group 3 which will be upcased ${3:/upcase}.

See regex101 demo.

Mark
  • 143,421
  • 24
  • 428
  • 436