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

如何用C#正则表达式提取字符串中的日期及含till present的时段

Fixing Your Date Range Extraction Regex in C#

Let's get your date range extraction working properly! The issue with your current regular expression is that it's built to match standalone, full-line date strings (like a single line containing only a valid date), not to pull out a date range from longer text. Here's how to fix this:

Step 1: Use a Targeted Regex for Date Ranges

We need a pattern that specifically matches your desired format: a start date, followed by to, then either till present or another end date. Here's the simplified regex:

string rx = @"\d{1,2} [A-Za-z]{3} \d{4} to (?:till present|\d{1,2} [A-Za-z]{3} \d{4})";

Breakdown of the Regex:

  • \d{1,2}: Matches 1 or 2 digits for the day (e.g., 13 or 5)
  • [A-Za-z]{3}: Matches 3-letter month abbreviations (case-insensitive, so Nov, nov, DEC all work)
  • \d{4}: Matches 4-digit year (e.g., 2014)
  • to: Explicitly matches the "to" separator with surrounding spaces
  • (?:till present|\d{1,2} [A-Za-z]{3} \d{4}): A non-capturing group that matches either the phrase till present OR another full date

Step 2: Updated C# Code

Replace your existing regex with the one above, and adjust the matching logic to properly extract the full range:

static void Main(string[] args)
{
    string str = "Web Application Developer in Acme Infosystem Mohali from 13 Nov 2014 to till present yii2 framework and Node JS. ";
    string rx = @"\d{1,2} [A-Za-z]{3} \d{4} to (?:till present|\d{1,2} [A-Za-z]{3} \d{4})";
    
    Regex ptrn = new Regex(rx);
    Match match = ptrn.Match(str);
    
    if (match.Success)
    {
        Console.WriteLine("Extracted date range: " + match.Value);
    }
    else
    {
        Console.WriteLine("No date range found.");
    }
}

Step 3: Test Results

When you run this code, it will output:

Extracted date range: 13 Nov 2014 to till present

If your input string has a specific end date instead of till present (e.g., 13 Nov 2014 to 25 Dec 2023), the regex will capture that full range too.

Optional: Case Insensitivity

If you want the regex to work regardless of capitalization (e.g., TILL PRESENT or nov), add the RegexOptions.IgnoreCase flag when creating the regex:

Regex ptrn = new Regex(rx, RegexOptions.IgnoreCase);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:00:35