如何用C#正则表达式提取字符串中的日期及含till present的时段
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.,13or5)[A-Za-z]{3}: Matches 3-letter month abbreviations (case-insensitive, soNov,nov,DECall 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 phrasetill presentOR 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

