Regular Expressions in TypeScript: A Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in TypeScript: From Theory to Practice

Regular expressions (regexp or regex) are a powerful tool for searching, replacing, and validating strings based on a given pattern. In TypeScript, as in JavaScript, regular expressions are a built-in language feature. This article will help you master the syntax, learn to apply regex in practice, and avoid common mistakes.



What is a Regular Expression and How to Create It in TypeScript

A regular expression is a sequence of characters that describes a search pattern. In TypeScript, there are two ways to create a regular expression:

  • Literal syntax: /pattern/flags
  • RegExp constructor: new RegExp('pattern', 'flags')

The first method is convenient for static patterns, the second when the pattern is formed dynamically.

// Literal syntaxconst emailPattern: RegExp = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;

// RegExp constructorconst dynamicPattern: string = "hello";const regexFromString: RegExp = new RegExp(dynamicPattern, "gi");

console.log(emailPattern.test("test@example.com")); // trueconsole.log(regexFromString.test("Hello world")); // true


Basic Methods for Working with Regular Expressions

In TypeScript, three key methods are available for working with regex. Let's look at each of them with examples.



The test() method — checking for a match

Returns true or false. Ideal for validation.

const hasNumber: RegExp = /\\d+/;console.log(hasNumber.test("abc123")); // trueconsole.log(hasNumber.test("abc"));    // false


The exec() method — detailed search

Returns an array with the match and additional information (index, input string). When using the g flag, it remembers the position of the last match.

const wordPattern: RegExp = /(\\w+)\\s(\\w+)/;const result = wordPattern.exec("Hello TypeScript");if (result) {    console.log(`Full match: ${result[0]}`); // Hello TypeScript    console.log(`First group: ${result[1]}`);      // Hello    console.log(`Second group: ${result[2]}`);      // TypeScript    console.log(`Index: ${result.index}`);          // 0}


The match() method — finding all matches

Called on a string, not on a regular expression. With the g flag, it returns an array of all matches.

const text: string = "Price: 100 rub, discount: 20 rub";const prices: RegExp = /\\d+/g;const foundPrices: string[] | null = text.match(prices);console.log(foundPrices); // ['100', '20', '0']


Syntax and Commonly Used Characters

To write effective regular expressions, you need to know the basic characters and their meanings.

  • . — any character except newline
  • \\d — digit (equivalent to [0-9])
  • \\w — letter, digit, or underscore ([a-zA-Z0-9_])
  • \\s — any whitespace character (space, tab, newline)
  • ^ — start of string
  • $ — end of string
  • * — 0 or more repetitions
  • + — 1 or more repetitions
  • ? — 0 or 1 repetition (makes quantifier lazy)
  • [] — character set (e.g., [a-z] — all lowercase letters)
  • () — capturing group
  • | — logical OR
// Examples of character usageconst phonePattern: RegExp = /^\\+?7?\\d{10}$/;console.log(phonePattern.test("+79161234567")); // true

const datePattern: RegExp = /^\\d{2}\\.\\d{2}\\.\\d{4}$/;console.log(datePattern.test("31.12.2023")); // true\

Blogs

Book Recommendations