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

Angular TypeScript正则需求:提取连字符后最后一段纯数字

提取字符串中最后一个“-”后的纯数字部分

我有以下5条输入文本:

A-01
AB - A2-01:xyz word (*)
AB - A3-02a:xyz word (*):xyz word (*)
AB - A-01:xyz word (*)
xyz-word  (*)

需要提取每条文本中最后一个“-”后的纯数字部分,预期输出如下:

01
01
02
01
empty(返回空值)

目前使用正则 input.match("[^-]+$")[0] 仅对第一条输入有效,其余输入会返回数字后的多余字符,需要在Angular TypeScript中解决这个匹配问题。


解决方案

可以使用精准匹配的正则表达式结合TypeScript函数实现需求:

核心正则表达式

const regex = /-(\d+)[^\d]*$/;

正则逻辑说明:

  • -:定位到字符串中的最后一个短横线
  • (\d+):捕获短横线后连续的数字序列(这就是我们要提取的目标内容)
  • [^\d]*$:匹配数字之后的任意非数字字符,直到字符串结尾,确保不会把后续多余内容带入结果

TypeScript实现代码

function extractTargetNumber(input: string): string {
  const matchResult = input.match(/-(\d+)[^\d]*$/);
  // 匹配到结果则返回捕获的数字,否则返回空值标记
  return matchResult ? matchResult[1] : 'empty(返回空值)';
}

// 测试验证
const testCases = [
  'A-01',
  'AB - A2-01:xyz word (*)',
  'AB - A3-02a:xyz word (*):xyz word (*)',
  'AB - A-01:xyz word (*)',
  'xyz-word  (*)'
];

testCases.forEach(item => {
  console.log(extractTargetNumber(item));
});

运行后输出结果完全符合预期:

01
01
02
01
empty(返回空值)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:00:50