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

PHP与C#正则提取mm/dd/yyyy日期的适配问题求助

在C#中提取mm/dd/yyyy格式日期的正则问题解决方法

我懂你遇到的这个坑!之前在PCRE环境里测试完美的正则表达式,放到C#里突然失效,大概率是字符串转义规则在搞鬼,咱们一步步来解决:

问题根源

在正则测试工具里写正则时,\是正则引擎的转义符(比如\d代表数字),但在C#的普通字符串中,\是字符串本身的转义符(比如\n表示换行)。如果你直接把PCRE里的正则复制到C#普通字符串中,\d会被当成无效的字符串转义序列,导致正则引擎接收到的表达式完全不是你想要的。

解决办法

有两种方式可以正确传递正则表达式给C#的Regex类:

  1. 使用逐字字符串(推荐)
    在字符串前加@前缀,这样字符串里的\不会被C#解析为转义符,直接原封不动传给正则引擎:

    Regex rx = new Regex(@"\d{1,2}\/\d{1,2}\/\d{4}\b");
    
  2. 手动转义所有反斜杠
    如果不想用逐字字符串,就把正则里的每个\替换成\\:

    Regex rx = new Regex("\\d{1,2}\\/\\d{1,2}\\/\\d{4}\\b");
    

完整测试代码

这里给你一个可直接运行的示例,验证提取逻辑:

using System;
using System.Text.RegularExpressions;

class DateExtractor
{
    static void Main()
    {
        string input = "The quick brown fox on 4/26/2018 decided to jump over the moon";
        Regex dateRegex = new Regex(@"\d{1,2}\/\d{1,2}\/\d{4}\b");
        
        Match dateMatch = dateRegex.Match(input);
        if (dateMatch.Success)
        {
            Console.WriteLine($"提取到的日期:{dateMatch.Value}");
        }
        else
        {
            Console.WriteLine("未找到符合格式的日期");
        }
    }
}

运行这段代码会输出:提取到的日期:4/26/2018

额外优化:验证日期合法性

如果你不仅要提取格式匹配的字符串,还要确保它是有效日期(比如避免出现13/32/2024这种无效值),可以在提取后用DateTime.TryParseExact验证:

if (dateMatch.Success)
{
    string dateStr = dateMatch.Value;
    if (DateTime.TryParseExact(dateStr, "M/d/yyyy", null, System.Globalization.DateTimeStyles.None, out DateTime validDate))
    {
        Console.WriteLine($"提取到的有效日期:{validDate:MM/dd/yyyy}");
    }
    else
    {
        Console.WriteLine($"提取到的字符串「{dateStr}」不是合法日期");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:53:10