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

如何更高效地使用正则表达式提取日期序列中的最后一个数字?

Better Regex Approaches to Extract the Last Date Number

Great question! That reverse-string workaround gets the job done, but there are much cleaner regex-based ways to grab the final numeric date component without needing to flip your string back and forth. Let’s break down a couple of solid alternatives:

Option 1: Directly Target the Final Date with End-of-String Anchoring

Instead of reversing, you can use regex to anchor to the end of the text and match the last number (along with its optional ordinal suffix like st, nd, etc.). Here’s a regex that does exactly that:

(\d{1,2})(?:st|nd|rd|th)?\s*$

How it works:

  • (\d{1,2}): Captures 1 or 2 digits (your target date number) into a group.
  • (?:st|nd|rd|th)?: Matches the optional ordinal suffix without capturing it (the ?: makes it a non-capturing group).
  • \s*$: Matches any trailing whitespace and anchors the pattern to the end of the string, ensuring we only get the last date entry.

For your example text:

June 8th, 11th, 15th, 16th, 18th, 23rd

This regex will capture 23 as the first (and only) group.

Option 2: Match All Date Numbers, Then Pick the Last One

If you might need all the date numbers later (not just the last), you can use a regex to find every numeric date component in the text, then grab the last element from the match results. Here’s the pattern:

\b\d{1,2}(?=(?:st|nd|rd|th))

How it works:

  • \b: Ensures we don’t match digits that are part of longer words (a word boundary).
  • \d{1,2}: Matches 1 or 2 digits.
  • (?=(?:st|nd|rd|th)): A positive lookahead that checks the digits are followed by an ordinal suffix (without including the suffix in the match).

When you run this as a global match on your example text, you’ll get an array like ["8", "11", "15", "16", "18", "23"] — just take the last element of this array for your target number.

Bonus: Optimize Your First Date Extraction

While we’re at it, you can tweak your initial first-date regex to also handle ordinal suffixes and be a bit more precise:

\b(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\w*\s(\d{1,2})(?:st|nd|rd|th)?

This captures the first date’s number (e.g., 8 from your example) while accounting for any ordinal suffix attached to it.

Why These Are Better Than the Reverse Trick

  • More intuitive: No mental gymnastics with string reversal — the regex directly expresses what you’re looking for.
  • Maintainable: Other developers reading your code won’t have to decode why you’re flipping strings.
  • Flexible: Option 2 lets you access all date numbers if you need them later, without rewriting logic.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:29:29