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

技术问询:如何从正则表达式匹配结果提取日期的日份?

Extract the Day from Date Match Results

Hey there! Let's get this sorted for you. I see you're trying to pull the day part from a date formatted as month/day/year, but your current approach has a small issue—let's fix that.

The Problem with Your Current Code

Your line console.log(/\d{2}/.exec(date)); looks for two-digit numbers starting at the beginning of the string. For "4/15/91" it might accidentally grab the right value, but for "11/2/2015" it'll pick the month "11" instead of the day "2". Worse, if the day is a single digit, this regex won't even find it at all. Not reliable!

The Correct Approach: Use Your Captured Groups

You already set up a regex with capturing groups ((\d+)\/(\d+)\/(\d+)), which splits the date into exactly the parts you need. When you run re.exec(date), it returns an array where:

  • result[0]: The full matched date string (e.g., "4/15/91")
  • result[1]: First captured group → month (e.g., "4" or "11")
  • result[2]: Second captured group → day (e.g., "15" or "2")
  • result[3]: Third captured group → year (e.g., "91" or "2015")

To get the day, you just need to access result[2] directly!

Working Code Example

var re = /(\d+)\/(\d+)\/(\d+)/;

// Test case 1: 4/15/91
var date1 = "4/15/91";
var result1 = re.exec(date1);
console.log(result1[2]); // Outputs: "15"

// Test case 2: 11/2/2015
var date2 = "11/2/2015";
var result2 = re.exec(date2);
console.log(result2[2]); // Outputs: "2"

This works perfectly for both single-digit and double-digit days, since your original regex uses \d+ (matches one or more digits) for each part—no more missing single-digit days or grabbing the wrong number!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:27:32