DEV Community

Cover image for Find and replace like a pro. Regular expressions in VS Code
Maks Vozbraniuk
Maks Vozbraniuk

Posted on • Edited on

Find and replace like a pro. Regular expressions in VS Code

Table of contents:

What is regular expressions?

Regular expressions (also called regex) are patterns used to match character combinations in strings [MDN]

For example, regex /popular|expressions/ will match word expressions in sentence "Regular expressions entered popular use from 1968".

Regexp example

Capturing groups

Groups group multiple patterns as a whole, and capturing groups provide extra submatch information when using a regular expression pattern to match against a string. [MDN]

Usually, to create capturing group you should use parentheses and put group regex into it. It’s very convinient when you want to use this group later.

For example we can use /const (.*) = / to capture variable name (getUser) from code const getUser = () => {...} into group.

Regexp group example

JS Example

In JavaScript as a result of .match() we get an array where first item is a whole match and other items are captured groups.

const text = "const getUser = () => {…}";
const regex = /const (.*) = /;

const match = text.match(regex);
console.log(match); // ['const getUser = ', 'getUser']
Enter fullscreen mode Exit fullscreen mode

Regex in VS Code

In VS Code you can efficiently search and replace some text in your project. Often you don't need regex for that. But sometimes regular expressions can save a lot of time (for instance, during refactoring).

VS Code allows us to use captured groups in replace section as $1 $2 $3 $n (where 1,2,3..n is a group number)

For example, in React you can easily switch between general TS function types to React.FC types:

VS Code replace example (to React.FC)

VS Code replace example (from React.FC)

Conclusion

Regular expressions is a powerful tool when you want to search some patterns in text. As developers we can use it not only in the code itself (e.g. phone number validation), but also to simplify some tasks we face.

If you want to learn more about regular expressions, I want to suggest you these resources:

Top comments (1)

Collapse
 
schemetastic profile image
Schemetastic (Rodrigo)

Hello! Welcome to the DEV community.

Interesting post! regex 101 is a great application for testing regular expressions, you know, a cool website I have found to learn regex is RegexLearn, hope this helps.