TypeScript 正则表达式示例:完整指南

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

TypeScript 正则表达式:从理论到实践

\n

正则表达式 (RegExp) 是用于搜索、替换和验证字符串的强大工具。在 TypeScript 中,它们的工作方式与 JavaScript 相同,但增加了严格的类型检查,从而简化了调试并提高了代码的可靠性。在本文中,我们将介绍 TypeScript 中正则表达式的语法、方法和实际使用示例。

\n\n

在 TypeScript 中创建正则表达式

\n

在 TypeScript 中,有两种创建 RegExp 的方法:字面量方式和构造函数方式。两种方式都有类型定义,并返回类型为 RegExp 的对象。

\n\n

字面量语法

\n

最简单且最常用的方法是将模式放在斜杠之间。标志写在第二个斜杠之后。

\n
// 不区分大小写搜索单词 "hello"\nconst pattern: RegExp = /hello/i;\nconsole.log(pattern.test('Hello World')); // true
\n\n

RegExp 构造函数

\n

当模式需要动态构建时,构造函数非常方便。第一个参数是包含模式的字符串,第二个参数是标志。

\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

TypeScript 中 RegExp 的主要方法

\n

TypeScript 继承了 JavaScript 中所有用于处理正则表达式的方法。让我们看看最常用的几个。

\n\n

test() — 检查是否存在

\n

test() 方法返回 true 或 false。对于表单验证非常有用。

\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() — 详细搜索

\n

exec() 返回一个包含匹配项、索引和分组的数组。如果没有匹配项,则返回 null。

\n
const datePattern: RegExp = /(\\d{2})\\.(\\d{2})\\.(\\d{4})/;\nconst result: RegExpExecArray | null = datePattern.exec('Сегодня 15.03.2025');\nif (result) {\n  console.log(`День: ${result[1]}, Месяц: ${result[2]}, Год: ${result[3]}`);\n  // День: 15, Месяц: 03, Год: 2025\n}
\n\n

字符串的 match() 和 matchAll() 方法

\n

match() 方法在字符串上调用,并接受一个 RegExp 作为参数。要全局搜索所有匹配项,请使用 matchAll()。

\n
const text: string = 'Код 123, код 456, код 789';\nconst numbers: RegExpMatchArray | null = text.match(/\\d+/g);\nconsole.log(numbers); // ['123', '456', '789']\n\n// matchAll() 返回一个迭代器\nconst matches: IterableIterator<RegExpMatchArray> = text.matchAll(/(\\d+)/g);\nfor (const match of matches) {\n  console.log(`Найдено число: ${match[1]}`);\n}
\n\n

TypeScript 中正则表达式的实用示例

\n

现在,让我们将理论应用到实际任务中。所有示例都考虑了 TypeScript 的严格类型检查。

\n\n

示例 1:验证电子邮件地址

\n

创建一个检查电子邮件地址有效性的函数。使用类型化的正则表达式。

\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

示例 2:从字符串中提取数字

\n

通常需要从文本中获取所有数字。使用带有 g 标志的全局搜索。

\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('Цена: 2500 руб, скидка 300 руб');\nconsole.log(result); // [2500, 300]
\n\

博客

书籍推荐