TypeScript中正则表达式的用法及实际应用_javascript技巧
正则模式是固定的、已知的
不需要动态构建正则
需要更好的可读性
使用构造函数语法:
在程序运行时(而非编写代码时)根据需要创建或修改正则表达式模式。
作用:使匹配不区分大小写
作用:查找所有匹配项,而不是在第一个匹配后停止
作用:使 ^ 和 $ 匹配每行的开头和结尾,而不是整个字符串的开头和结尾
const multiLineText = `First lineSecond lineThird line`;// 不使用 m 修饰符console.log(/^Second/.test(multiLineText)); // false//在整个字符串的开头位置尝试匹配 "Second"// 使用 m 修饰符console.log(/^Second/m.test(multiLineText)); // true
作用:正确处理大于 \uFFFF 的 Unicode 字符
const emojiText = '😊 笑脸';// 不使用 u 修饰符console.log(/^.$/.test(emojiText)); // false (无法正确匹配emoji)// 使用 u 修饰符console.log(/^.$/u.test(emojiText)); // true (正确匹配单个emoji字符)// 匹配特定Unicode字符console.log(/\p{Emoji}/u.test('😊')); // trueconsole.log(/\p{Script=Han}/u.test('汉')); // true (匹配汉字)
作用:使 . 匹配包括换行符在内的任意字符
const textWithNewline = 'Hello\nWorld';// 不使用 s 修饰符console.log(/Hello.World/.test(textWithNewline)); // false (.不匹配换行符)// 使用 s 修饰符console.log(/Hello.World/s.test(textWithNewline)); // true// 替代方案(不使用s修饰符)console.log(/Hello[\s\S]World/.test(textWithNewline)); // true
可以同时使用多个修饰符,顺序无关紧要:
// 不区分大小写 + 全局匹配 + 多行模式const regex = /^hello/gim;const text = `Hello worldhello everyoneHELLO there`;console.log(text.match(regex)); // ["Hello", "hello", "HELLO"]
const regex = /hello/;// test() - 测试是否匹配regex.test('hello world'); // true// exec() - 执行搜索,返回匹配结果或 nullconst result = regex.exec('hello world');console.log(result?.[0]); // "hello"
const str = 'Hello world, hello TypeScript';// match() - 返回匹配结果str.match(/hello/gi); // ["Hello", "hello"]// search() - 返回匹配位置的索引str.search(/world/); // 6// replace() - 替换匹配的子串str.replace(/hello/gi, 'Hi'); // "Hi world, Hi TypeScript"// split() - 使用正则分割字符串'one,two,three'.split(/,/); // ["one", "two", "three"]
确保匹配从字符串开头开始,防止前面有其他字符
邮箱地址必须包含一个@符号
正则表达式中的点号.
确保匹配直到字符串结束,防止后面有其他字符
核心的正则表达式是 /[?&]([^=#]+)=([^]*)/g,让我们分解它的每个部分:
function checkPasswordStrength(password: string): 'weak' | 'medium' | 'strong' { // 至少8个字符 if (password.length < 8) return 'weak'; // 弱: 只有字母或数字 if (/^[a-zA-Z]+$/.test(password) || /^\d+$/.test(password)) { return 'weak'; } // 中: 包含字母和数字 if (/^(?=.*[a-zA-Z])(?=.*\d).+$/.test(password)) { // 强: 包含字母、数字和特殊字符 if (/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).+$/.test(password)) { return 'strong'; } return 'medium'; } return 'weak';}
(?=pattern) 是正向先行断言的基本形式,表示:
这个表达式由两个正向先行断言组成,分别检查密码中是否包含字母和数字。
到此这篇关于TypeScript中正则表达式的用法及实际应用的文章就介绍到这了,更多相关TS中正则表达式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
本文地址: https://www.earthnavs.com/jishuwz/10b26c5c5c89009fb677.html























