DEV Community

Le Vuong
Le Vuong

Posted on

My commonly used regex

Regex is indispensable for developers. Below are some of my notes when working with Regex.

Notes:

  • Please try examples in this post with VSCode.
  • If you are on Windows, use \r\n instead of \n for line-ending.

Use OR in regex expression

  • Regex OR expression allow choosing 1 of multiple options.
  • Syntax: wrap the OR expression in parentheses.

Ex: (option1|option2)

Search/remove empty lines

  • Use vscode replace function (Ctrl-H or Ctrl-Shift-H)
  • Source: ^$\n
  • Target: (Leave this field empty)
  • Note: ^\s*$\n - use this pattern if you want to replace lines with only spaces too.

Search lines NOT matching a string

  • Use this pattern to search lines that NOT containing abc: ^((?!abc).)*$
  • ?! is negative look-ahead operator. See also: look-behind, look around operators.
  • Note: this pattern is processing-heavy.

Shell alternatives

  • Many text processing tasks can be done by CLI tools, so why not use that instead? The shell commands like grep, sed, or awk are also faster and easier to maintain.

  • Use my Shell Command 2 extension to execute shell commands on selected text right from inside VSCode.

Regex Variants

  • VS Code uses JavaScript-style regex (and PCRE2 for global search)
  • Visual Studio use an MS specific Regex version

And, as always, use and practice a new skill frequently.

Top comments (0)