You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何按指定通配符模式匹配截取目标字符串

Node.js 通配符模式字符串捕获实现方案

核心思路是将输入的带*通配符的匹配模式转换为合法正则表达式,通过全局匹配提取所有符合规则的字符片段,同时兼容单匹配、多匹配两种场景。

  • 先对模式串里的正则特殊元字符做转义,避免.、?这类字符被误解析为正则规则
  • 将通配符*替换为对应匹配规则:针对示例里的空格分隔文件名场景,*匹配连续非空白字符即可
  • 开启正则全局匹配模式,一次性提取所有符合结果,按匹配数量返回对应格式

实现代码

function matchPattern(inputStr, wildcardPattern) {
  // 转义除*外的所有正则特殊字符
  const escapedPattern = wildcardPattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
  // 将*替换为非空白字符匹配规则,适配空格分隔的片段捕获
  const regexSource = escapedPattern.replace(/\*/g, '[^\\s]+');
  // 生成全局匹配正则
  const matchRegex = new RegExp(regexSource, 'g');
  // 执行匹配
  const matchResults = inputStr.match(matchRegex);

  if (!matchResults) return null;
  // 单结果返回字符串,多结果返回数组,符合需求要求
  return matchResults.length === 1 ? matchResults[0] : matchResults;
}

场景测试

单匹配场景

const inputString = '     abc 1 2 3  white_rabbit_123_456_789.txt pqr ';
const pattern = 'white_rabbit_*_*_*.txt';
console.log(matchPattern(inputString, pattern));
// 输出: white_rabbit_123_456_789.txt

多匹配场景

const inputString = '     abc 1 2 3  white_rabbit_123_456_789.txt pqr \n  white_rabbit_312_456_888.txt';
const pattern = 'white_rabbit_*_*_*.txt';
console.log(matchPattern(inputString, pattern));
// 输出: ['white_rabbit_123_456_789.txt', 'white_rabbit_312_456_888.txt']

适配调整说明

如果你的匹配场景里*需要匹配包含空格的内容,可以将*对应的匹配规则从[^\s]+替换为.+?,注意根据实际场景加边界判断避免出现过度匹配的问题。

内容的提问来源于stack exchange,提问作者Pavan Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 17:09:19