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

如何通过正则表达式提取字符串指定子串并封装为可复用函数

解决方案

1 问题原因说明

  • 重复声明报错:同一个块级作用域下用const两次声明变量_,违反了块级作用域变量不可重复声明的规则
  • 原有封装函数错误:函数内部没有使用传入的text参数,而是写死了测试字符串,无法处理输入的文本内容
  • 缺少异常兼容:如果输入文本中没有匹配的密码格式,match会返回null,直接解构会抛出错误

2 正确的可复用提取函数实现

const extractPassword = (text: string): string | null => {
  // 对传入的文本做 trim 后匹配正则
  const matchResult = text.trim().match(/Your\s+password\s+(\w+)/)
  // 匹配成功返回捕获到的密码,匹配失败返回 null,可根据业务需求调整为抛出错误或返回空字符串
  return matchResult ? matchResult[1] : null
}

3 使用示例

const retailerPassword = extractPassword(retailerMessage.html.body)
console.log(retailerPassword)

const recipentPassword = extractPassword(recipentMessage.html.body)
console.log(recipentPassword)

可选优化点

  • 如果你的密码允许包含除字母、数字、下划线之外的特殊字符,可以把正则里的\w+替换为更适配的规则,比如[A-Za-z0-9!@#$%^&*]+这类自定义字符集
  • 如果业务要求密码不存在时必须抛出异常,可以把返回 null 的逻辑替换为抛错,避免后续逻辑拿到空值出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:54:03