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

Angular中如何使用正则提取字符串的首个连续数字序列

问题解决方法

你当前代码输出全部连续数字拼接结果的核心原因是正则表达式携带了g全局匹配修饰符,会遍历整个字符串提取所有符合规则的连续数字组,两种修改方案如下:

方案1:保留现有正则,直接取第一个匹配结果

不需要修改正则规则,直接对返回的匹配数组取下标为0的元素即可,注意增加空值判断避免无数字时报错:

const newVar = 'aaaa123aaaa6'
const regex = /\d+/g;
const matches = newVar.match(regex);
// 无匹配结果时返回空字符串,可根据需求调整默认值
const firstContinuousNumbers = matches ? matches[0] : '';
console.log(firstContinuousNumbers) // 输出 123

方案2:移除全局修饰符,仅匹配第一组结果

去掉正则的g修饰符后,正则匹配到第一组符合规则的结果就会停止遍历,性能更优:

const newVar = 'aaaa123aaaa6'
// 移除g全局修饰符
const regex = /\d+/;
const matchResult = newVar.match(regex);
const firstContinuousNumbers = matchResult ? matchResult[0] : '';
console.log(firstContinuousNumbers) // 输出 123

效果验证

两种方案都可以满足你的需求:

  • 输入aaa123aaaa95,返回结果为123
  • 输入bbbb2bbb393,返回结果为2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:54:07