js实现匹配
正则表达式匹配
使用JavaScript的RegExp对象进行字符串匹配。通过test()方法检查字符串是否匹配模式,或使用exec()获取匹配细节。
const regex = /hello/i;
const str = 'Hello, world!';
console.log(regex.test(str)); // true
字符串方法匹配
JavaScript内置字符串方法如includes()、indexOf()或match()可直接进行基础匹配。
const str = 'Find the substring';
console.log(str.includes('sub')); // true
console.log(str.indexOf('the') !== -1); // true
模糊匹配算法
实现Levenshtein距离算法进行相似度匹配,适用于拼写纠错等场景。
function levenshtein(a, b) {
const matrix = Array(b.length + 1).fill(null).map(() =>
Array(a.length + 1).fill(null));
for (let i = 0; i <= a.length; i++) matrix[0][i] = i;
for (let j = 0; j <= b.length; j++) matrix[j][0] = j;
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
const cost = a[i-1] === b[j-1] ? 0 : 1;
matrix[j][i] = Math.min(
matrix[j][i-1] + 1,
matrix[j-1][i] + 1,
matrix[j-1][i-1] + cost
);
}
}
return matrix[b.length][a.length];
}
模式匹配库
使用第三方库如minimatch进行glob模式匹配,或fuse.js实现模糊搜索。
const minimatch = require('minimatch');
console.log(minimatch('file.txt', '*.txt')); // true
const fuse = new Fuse(['apple', 'banana'], { threshold: 0.3 });
console.log(fuse.search('app')); // 返回匹配结果
高级正则技巧
利用正则表达式的捕获组、前瞻后顾等特性实现复杂匹配逻辑。

// 提取日期
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const dateMatch = '2023-05-15'.match(dateRegex);
console.log(dateMatch.slice(1)); // ['2023', '05', '15']
// 密码强度验证
const passwordRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).{8,}$/;
console.log(passwordRegex.test('Pass1234')); // true






