Steve Kinney

Visual Studio Code

Using Snippets with Regular Expressions in Visual Studio Code

Suppose you want to generate a TypeScript constant name based on the filename, converting hello-world.ts into HELLO_WORLD. Capture groups and regex replacements are your allies here:

"Uppercase Constant from Filename": {
  "prefix": "constfile",
  "body": [
    "const ${TM_FILENAME_BASE/(.*)/${1:/upcase}/} = '$1';"
  ],
  "description": "Creates an uppercase constant from filename"
}

But hold on—this snippet currently only makes the whole filename uppercase without handling dashes. To tackle that, try this enhanced regex transformation:

"Snake Case Constant from Filename": {
  "prefix": "snakeconst",
  "body": [
    "const ${TM_FILENAME_BASE/([a-zA-Z0-9]+)([-_]*)/${1:/upcase}${2:+_}/g} = '$1';"
  ],
  "description": "Transforms filename (e.g., hello-world) into UPPER_SNAKE_CASE constant"
}

Now, hello-world.ts magically becomes:

const HELLO_WORLD = 'hello-world';

The +_ conditional (${2:+_}) adds underscores only if dashes or underscores are present between segments, ensuring you never end up with trailing underscores.

Conditional Replacements with Regex

Sometimes, you want conditionals in your snippets. For example, converting a selected string into singular or plural form:

"Pluralize selected word": {
  "prefix": "pluralize",
  "body": "${TM_SELECTED_TEXT/(.*?)(y|s)?$/${2:?${2/(y|s)/${2:/downcase}/}es:${1}s}/}",
  "description": "Pluralizes the selected English word"
}

Here’s how it works:

  • If the selected text ends in y or s, it pluralizes correctly:
    • citycities
    • classclasses
  • Otherwise, it simply adds an s:
    • dogdogs

Regex captures ((.*?) and (y|s)?) and conditionals (${2:?…:…}) are the secret sauce that make this possible.

This is the Standard Issue Warning for Regular Expressions

Complex regex patterns are powerful but can quickly get hairy. Always test your snippets with varied input to ensure consistent behavior. Nobody likes regex-induced bugs at 2 AM.

Last modified on .