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".
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.
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']
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:
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:
-
regex101 - there you can test your regular expressions and get some hints
Regular Expressions course on FreeCodeCamp (as part of JavaScript Algorithms and Data Structures)
Top comments (1)
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.