TypeScript正则表达式示例

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

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

开始课程

TypeScript中的正则表达式:语法、方法与示例



正则表达式(regex)是处理字符串的强大工具。在TypeScript中,它们不仅可以让你搜索、替换和验证文本,还能对结果进行严格的类型化。本文将涵盖在TypeScript中使用RegExp的所有方面:从基本语法到带有代码示例的高级技术。



1. 在TypeScript中创建正则表达式



在TypeScript中,与JavaScript一样,有两种创建正则表达式的方式:



字面量语法

最常见且方便的方法是使用斜杠:



const pattern: RegExp = /hello/gi;


这里的g表示全局搜索,i表示不区分大小写。RegExp类型会被自动推断,但为了提高可读性,也可以显式指定。



RegExp构造函数

当模式是动态形成时使用:



const searchTerm: string = "world";const dynamicPattern: RegExp = new RegExp(searchTerm, "gi");


第二个参数是包含标志的字符串。返回类型为RegExp。



2. 基本的RegExp和字符串方法



TypeScript继承了所有JavaScript方法,但为它们增加了严格的类型化。让我们通过示例来看看关键方法。



test()方法

检查字符串中是否存在匹配项。返回boolean类型。



const emailRegex: RegExp = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;const email: string = "user@example.com";

const isValid: boolean = emailRegex.test(email);console.log(isValid); // true


exec()方法

搜索匹配项并返回详细信息。返回RegExpExecArray | null。



const text: string = "Price: 1500 rubles, discount: 200 rubles";const pricePattern: RegExp = /(\\d+)\\s*rubles/g;

let match: RegExpExecArray | null;while ((match = pricePattern.exec(text)) !== null) { console.log(`Found: ${match[0]}, number: ${match[1]}`);}// Output:// Found: 1500 rubles, number: 1500// Found: 200 rubles, number: 200


字符串的match()方法

工作方式类似于exec(),但在字符串上调用。返回RegExpMatchArray | null。



const phone: string = "Contacts: +7 (999) 123-45-67";const phoneRegex: RegExp = /\\+7\\s*\\(\\d{3}\\)\\s*\\d{3}-\\d{2}-\\d{2}/;

const result: RegExpMatchArray | null = phone.match(phoneRegex);if (result) { console.log(`Phone found: ${result[0]}`); // Phone found: +7 (999) 123-45-67}


replace()方法

用新字符串替换匹配项。返回string类型。支持使用回调函数进行复杂替换。



function formatDate(input: string): string {    const datePattern: RegExp = /(\\d{4})-(\\d{2})-(\\d{2})/;    return input.replace(datePattern, "$3.$2.$1");}

const isoDate: string = "2025-03-10";const formatted: string = formatDate(isoDate);console.log(formatted); // "10.03.2025"


split()方法

根据正则表达式分割字符串。返回string[]。



const data: string = "apple;pear;orange;banana";const items: string[] = data.split(/;\\s*/);console.log(items); // ["apple", "pear", "orange", "banana"]


3. 标志及其组合



标志控制正则表达式的行为。在TypeScript中,它们可以在字面量中设置,也可以作为构造函数的第二个参数设置。



标志描述示例
g全局搜索(所有匹配项)/ab/g
i不区分大小写

博客

书籍推荐