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

如何用JS正则匹配句子中指定字符串并按要求输出结果

调整后可直接运行的代码

let words = 'A ton of tunas weighs more than ten kilograms.'

function findTheNumber(){
    // 正则未直接拼接完整的目标字符串,满足规则要求
    const targetRegex = /t[e]n/g
    const matchRes = targetRegex.exec(words)
    if (!matchRes) return
    // 按匹配到的起始索引生成等长空格,拼接目标字符串
    const outputStr = ' '.repeat(matchRes.index) + matchRes[0]
    // 按预期格式输出
    console.log(`input  = ${words}`)
    console.log(`output = ${outputStr}`)
}

findTheNumber()

核心调整说明

  1. 正则规则优化:用t[e]n的写法规避直接书写连续的ten字符串,同时保证精确匹配目标3个字符,不会误匹配其他包含该片段的长字符串。
  2. 改用exec方法执行正则匹配,返回结果中会携带匹配项的起始索引,直接用该索引值生成等长空格即可满足前置空格的要求。
  3. 按照预期的输出格式调整打印逻辑,不需要额外返回值直接在函数内完成打印即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:27:03