TypeScript 正则表达式:从理论到实践
\n正则表达式 (RegExp) 是用于搜索、替换和验证字符串的强大工具。在 TypeScript 中,它们的工作方式与 JavaScript 相同,但增加了严格的类型检查,从而简化了调试并提高了代码的可靠性。在本文中,我们将介绍 TypeScript 中正则表达式的语法、方法和实际使用示例。
\n\n在 TypeScript 中创建正则表达式
\n在 TypeScript 中,有两种创建 RegExp 的方法:字面量方式和构造函数方式。两种方式都有类型定义,并返回类型为 RegExp 的对象。
字面量语法
\n最简单且最常用的方法是将模式放在斜杠之间。标志写在第二个斜杠之后。
\n// 不区分大小写搜索单词 "hello"\nconst pattern: RegExp = /hello/i;\nconsole.log(pattern.test('Hello World')); // true\n\nRegExp 构造函数
\n当模式需要动态构建时,构造函数非常方便。第一个参数是包含模式的字符串,第二个参数是标志。
\nconst 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\nTypeScript 中 RegExp 的主要方法
\nTypeScript 继承了 JavaScript 中所有用于处理正则表达式的方法。让我们看看最常用的几个。
\n\ntest() — 检查是否存在
\ntest() 方法返回 true 或 false。对于表单验证非常有用。
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\nexec() — 详细搜索
\nexec() 返回一个包含匹配项、索引和分组的数组。如果没有匹配项,则返回 null。
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() 方法
\nmatch() 方法在字符串上调用,并接受一个 RegExp 作为参数。要全局搜索所有匹配项,请使用 matchAll()。
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\nTypeScript 中正则表达式的实用示例
\n现在,让我们将理论应用到实际任务中。所有示例都考虑了 TypeScript 的严格类型检查。
\n\n示例 1:验证电子邮件地址
\n创建一个检查电子邮件地址有效性的函数。使用类型化的正则表达式。
\nfunction 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 标志的全局搜索。
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\