TypeScript 中的正则表达式:从理论到实践
正则表达式(regexp 或 regex)是一种强大的工具,用于根据指定模式搜索、替换和验证字符串。在 TypeScript 中,与 JavaScript 一样,正则表达式是语言的内置功能。本文将帮助您掌握语法,学习如何在实际中应用 regex,并避免常见错误。
什么是正则表达式以及如何在 TypeScript 中创建它
正则表达式是一系列描述搜索模式的字符。在 TypeScript 中,有两种创建正则表达式的方法:
- 字面量语法:
/模式/标志 - RegExp 构造函数:
new RegExp('模式', '标志')
第一种方法适用于静态模式,第二种方法适用于动态构建模式。
// 字面量语法const emailPattern: RegExp = /^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$/;
// RegExp 构造函数const dynamicPattern: string = "hello";const regexFromString: RegExp = new RegExp(dynamicPattern, "gi");
console.log(emailPattern.test("test@example.com")); // trueconsole.log(regexFromString.test("Hello world")); // true使用正则表达式的主要方法
在 TypeScript 中,有三种处理 regex 的关键方法。让我们通过示例逐一了解。
test() 方法 — 检查匹配
返回 true 或 false。非常适合验证。
const hasNumber: RegExp = /\\d+/;console.log(hasNumber.test("abc123")); // trueconsole.log(hasNumber.test("abc")); // falseexec() 方法 — 详细搜索
返回一个包含匹配项和额外信息(索引、原始字符串)的数组。使用 g 标志时,会记住上次匹配的位置。
const wordPattern: RegExp = /(\\w+)\\s(\\w+)/;const result = wordPattern.exec("Hello TypeScript");if (result) { console.log(`完整匹配: ${result[0]}`); // Hello TypeScript console.log(`第一组: ${result[1]}`); // Hello console.log(`第二组: ${result[2]}`); // TypeScript console.log(`索引: ${result.index}`); // 0}match() 方法 — 查找所有匹配项
在字符串上调用,而不是在正则表达式上。使用 g 标志时,返回所有匹配项的数组。
const text: string = "价格: 100 卢布, 折扣: 20 卢布";const prices: RegExp = /\\d+/g;const foundPrices: string[] | null = text.match(prices);console.log(foundPrices); // ['100', '20', '0']语法和常用字符
要编写有效的正则表达式,您需要了解基本字符及其含义。
.— 除换行符外的任何字符\\d— 数字(等价于[0-9])\\w— 字母、数字或下划线([a-zA-Z0-9_])\\s— 任何空白字符(空格、制表符、换行符)^— 字符串开头$— 字符串结尾*— 0 次或多次重复+— 1 次或多次重复?— 0 次或 1 次重复(使量词变为懒惰模式)[]— 字符集(例如,[a-z]— 所有小写字母)()— 捕获组|— 逻辑或
// 字符使用示例const 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\