Regular Expressions in TypeScript with Examples: A Complete Guide

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

\n

Regular expressions (RegExp) are a powerful tool for searching, replacing, and validating strings. In TypeScript, they work the same as in JavaScript but add strict typing, which simplifies debugging and increases code reliability. In this article, we will break down the syntax, methods, and real-world examples of using regular expressions in TypeScript.

\n\n

Creating Regular Expressions in TypeScript

\n

In TypeScript, there are two ways to create a RegExp: literal and via the constructor. Both options are typed and return an object of type RegExp.

\n\n

Literal Syntax

\n

The simplest and most commonly used method is to enclose the pattern in forward slashes. Flags are specified after the second slash.

\n
// Search for the word "hello" case-insensitively\nconst pattern: RegExp = /hello/i;\nconsole.log(pattern.test('Hello World')); // true
\n\n

RegExp Constructor

\n

The constructor is convenient when the pattern is formed dynamically. The first argument is a string with the pattern, the second is flags.

\n
const searchTerm: string = 'TypeScript';\nconst dynamicPattern: RegExp = new RegExp(searchTerm, 'gi');\nconsole.log('I love TypeScript and TypeScript is great'.match(dynamicPattern));\n// ['TypeScript', 'TypeScript']
\n\n

Basic RegExp Methods in TypeScript

\n

TypeScript inherits all JavaScript methods for working with regex. Let's look at the most popular ones.

\n\n

test() — Checking for a Match

\n

The test() method returns true or false. It is useful for form validation.

\n
const emailRegex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\nconst email: string = 'user@example.com';\nconsole.log(emailRegex.test(email)); // true
\n\n

exec() — Detailed Search

\n

exec() returns an array with the match, index, and groups. If there are no matches, it returns null.

\n
const datePattern: RegExp = /(\\d{2})\\.(\\d{2})\\.(\\d{4})/;\nconst result: RegExpExecArray | null = datePattern.exec('Today is 15.03.2025');\nif (result) {\n  console.log(`Day: ${result[1]}, Month: ${result[2]}, Year: ${result[3]}`);\n  // Day: 15, Month: 03, Year: 2025\n}
\n\n

match() and matchAll() for Strings

\n

The match() method is called on a string and takes a RegExp. For a global search of all matches, use matchAll().

\n
const text: string = 'Code 123, code 456, code 789';\nconst numbers: RegExpMatchArray | null = text.match(/\\d+/g);\nconsole.log(numbers); // ['123', '456', '789']\n\n// matchAll() returns an iterator\nconst matches: IterableIterator<RegExpMatchArray> = text.matchAll(/(\\d+)/g);\nfor (const match of matches) {\n  console.log(`Found number: ${match[1]}`);\n}
\n\n

Practical Examples of Regular Expressions in TypeScript

\n

Now let's apply the theory to real-world tasks. All examples are written with TypeScript's strict typing in mind.

\n\n

Example 1: Email Address Validation

\n

Let's create a function that checks the validity of an email. We'll use a typed regular expression.

\n
function isValidEmail(email: string): boolean {\n  const emailRegex: RegExp = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n  return emailRegex.test(email);\n}\n\nconsole.log(isValidEmail('test@mail.ru'));   // true\nconsole.log(isValidEmail('invalid-email'));  // false
\n\n

Example 2: Extracting Numbers from a String

\n

Often you need to get all numbers from text. We'll use a global search with the g flag.

\n
function extractNumbers(text: string): number[] {\n  const numberPattern: RegExp = /\\d+/g;\n  const matches: RegExpMatchArray | null = text.match(numberPattern);\n  return matches ? matches.map(Number) : [];\n}\n\nconst result: number[] = extractNumbers('Price: 2500 rub, discount 300 rub');\nconsole.log(result); // [2500, 300]
\n\

Blogs

Book Recommendations