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

如何用正则表达式从自由文本中提取指定格式的首个年份

纯正则方案匹配自由文本中的首个合法年份

需要编写正则表达式,匹配自由文本中出现的首个符合要求的年份:

  • 年份为4位数字,必须以20或21开头(例如2030、2199)
  • 不能匹配长数字串中的片段(比如20304050里的2030不能被匹配)
  • 要求纯正则实现,无需额外处理代码(允许匹配结果带后续的非数字字符,之后可截取前4位)

原代码中的三个正则无法适配所有测试用例,以下是修正后的方案:

最终正则表达式

如果只需要匹配年份并允许带后续非数字字符(之后截取前4位):

const regex = /(?:^|\D)2[01]\d{2}(?!\d)/

如果需要直接捕获年份本身(更方便提取):

const regex = /(?:^|\D)(2[01]\d{2})(?!\d)/

正则规则解释

  • (?:^|\D):非捕获组,匹配字符串开头或任意非数字字符,确保年份前不是数字(避免误匹配长数字串的前4位)
  • 2[01]\d{2}:核心匹配规则,精准匹配以20/21开头的4位数字
  • (?!\d):负向断言,确保年份后不是数字(避免匹配长数字串的片段)

测试验证

将原代码中的正则替换为上述表达式,修改后的测试代码如下:

const values = [
  '2025',
  '2150 is the year to match',
  'the year is 2030 see ref 2099662',
  'Should match the year here YEAR_2140 even though it has non numric chars preceeding it',
  'Should match the year at the end of a string like this - 2140',
  'ref 2099662 the year is 2140. And there is another sentence',
  'ref 2099662 the end of the string is the year 2140',
  'There is no year here 2055667'
]
console.log('   result', 'input string')

values.forEach((value, index) => {
  value = value.trim()
  const regex = /(?:^|\D)(2[01]\d{2})(?!\d)/
  const match = value.match(regex)
  const year = match ? match[1] : '     '

  console.log(`${index + 1}) ${year}, "${value}",`)
})

测试输出

result input string
1) 2025, "2025",
2) 2150, "2150 is the year to match",
3) 2030, "the year is 2030 see ref 2099662",
4) 2140, "Should match the year here YEAR_2140 even though it has non numric chars preceeding it",
5) 2140, "Should match the year at the end of a string like this - 2140",
6) 2140, "ref 2099662 the year is 2140. And there is another sentence",
7) 2140, "ref 2099662 the end of the string is the year 2140",
8)      , "There is no year here 2055667",

所有测试用例均被正确适配:

  • 单独年份、字符串末尾的年份能正常匹配
  • 长数字串中的片段(如2099662里的2099)不会被误识别
  • 前缀为非数字字符的年份(如YEAR_2140)能精准匹配
  • 无合法年份的文本返回空值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:03:22