You need to enable JavaScript to run this app. 如何使用正则表达式(regex)编写函数判断输入年份所属的正确世纪?
优惠活动
大模型
产品
解决方案
定价
更多

如何使用正则表达式(regex)编写函数判断输入年份所属的正确世纪?

现有代码的核心问题
  • 误把正则字符类[]当数字范围使用:[]的作用是匹配单个字符的规则,括号里的1001-1100会被解析为单个字符的ASCII范围,完全无法实现四位年份的区间匹配,这也是当前代码判断完全失效的核心原因。
  • 未加首尾锚定符^、$:如果不锚定字符串首尾,只要年份子串符合规则就会误判,比如输入11001会被错误匹配到11世纪的规则。
  • 多余的修饰符:ig里的i是忽略大小写,对数字完全没用;g是全局匹配,单年判断也不需要。
  • 世纪后缀错误:21对应的英文后缀是21st,不是21th。
适配需求的正则实现(仅用于练习正则)

正则完全可以实现该判断,只是写法非常繁琐,刚好符合练习正则语法的诉求。我们按照给定的年份区间规则,逐段拆解匹配逻辑:

function century(num) {
  // 显式把数字转为字符串,避免JS隐式转换的异常问题
  const yearStr = String(num);
  // 单独处理1000的特殊归属
  if (/^1000$/.test(yearStr)) {
    return '10th century';
  } else if (/^(10(0[1-9]|[1-9]\d)|1100)$/.test(yearStr)) {
    // 匹配1001-1100 11世纪
    return '11th century';
  } else if (/^(11(0[1-9]|[1-9]\d)|1200)$/.test(yearStr)) {
    // 匹配1101-1200 12世纪
    return '12th century';
  } else if (/^(12(0[1-9]|[1-9]\d)|1300)$/.test(yearStr)) {
    // 匹配1201-1300 13世纪
    return '13th century';
  } else if (/^(13(0[1-9]|[1-9]\d)|1400)$/.test(yearStr)) {
    // 匹配1301-1400 14世纪
    return '14th century';
  } else if (/^(14(0[1-9]|[1-9]\d)|1500)$/.test(yearStr)) {
    // 匹配1401-1500 15世纪
    return '15th century';
  } else if (/^(15(0[1-9]|[1-9]\d)|1600)$/.test(yearStr)) {
    // 匹配1501-1600 16世纪
    return '16th century';
  } else if (/^(16(0[1-9]|[1-9]\d)|1700)$/.test(yearStr)) {
    // 匹配1601-1700 17世纪
    return '17th century';
  } else if (/^(17(0[1-9]|[1-9]\d)|1800)$/.test(yearStr)) {
    // 匹配1701-1800 18世纪
    return '18th century';
  } else if (/^(18(0[1-9]|[1-9]\d)|1900)$/.test(yearStr)) {
    // 匹配1801-1900 19世纪
    return '19th century';
  } else if (/^(19(0[1-9]|[1-9]\d)|2000)$/.test(yearStr)) {
    // 匹配1901-2000 20世纪
    return '20th century';
  } else if (/^20(0[1-9]|10)$/.test(yearStr)) {
    // 匹配2001-2010,符合给定的输入上限要求
    return '21st century';
  } else {
    return undefined;
  }
}
// 测试用例运行结果完全符合预期
console.log(century(1756)); // 输出"18th century"
console.log(century(1555)); // 输出"16th century"
console.log(century(1000)); // 输出"10th century"
console.log(century(1001)); // 输出"11th century"
console.log(century(2005)); // 输出"21st century"
补充说明

这类正则实现仅适合用来熟悉字符组、锚定、分支匹配等语法,实际开发中完全不需要这么复杂,直接用Math.ceil(num / 100)就能快速计算世纪,再做后缀拼接即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 20:06:04