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

C#使用StreamReader与正则提取文本日期匹配数为0问题求助

问题排查及修复方案

你的代码核心问题为正则表达式语法错误,同时存在少量细节逻辑问题,具体排查和修复如下:

1. 核心错误:正则写法错误

你当前使用方括号[]包裹月份可选值,该用法完全不符合需求:

  • 方括号[]是字符组语法,仅匹配括号内的任意单个字符,你写的[Jan | Feb | Mar | ...]实际只会匹配J、a、n、|、空格等单个字符,完全无法匹配完整的月份名称。
  • 匹配多个可选的完整字符串,需要用()分组配合|实现,同时需要兼容June、December这类全写月份的匹配规则。

2. 其他可优化问题

  • 读取文件的流资源没有做自动释放,建议用using语句托管StreamReader生命周期,无需手动调用Close方法,避免内存泄漏。
  • 匹配成功后你打印的是整行内容inputdata,如果只需要打印匹配到的日期部分,可以直接取匹配结果m.Value。
  • 正则默认区分大小写,若需要兼容小写月份格式,可以新增RegexOptions.IgnoreCase参数。

修复后的完整代码

using System.Text.RegularExpressions;
using System.IO;

Console.WriteLine("Date Match");
Console.Write("Please enter the file name: ");
string filename = Console.ReadLine();
string fullname = @"C:\Work\" + filename;
int counter = 0;
if (File.Exists(fullname))
{
    Console.WriteLine("File exists!");
    // 用using自动管理流资源
    using StreamReader file3 = new StreamReader(fullname);
    string inputdata;
    // 修复正则:用分组匹配月份,兼容月份全写/缩写,添加单词边界避免误匹配
    Regex pattern1 = new Regex(@"\d{2}\s+(Jan|Feb|Mar|Apr|May|Jun[e]?|Jul|Aug|Sep|Oct|Nov|Dec(ember)?)\b");
     
    while ((inputdata = file3.ReadLine()) != null)
    {
        foreach(Match m in pattern1.Matches(inputdata))
        {
            // 按预期输出格式打印,去掉行尾的标点符号
            Console.WriteLine("The date found is: " + inputdata.TrimEnd(',', '.'));
            counter++;
        }
    }
    Console.WriteLine("The number of match is: " + counter + ".");
}
Console.ReadLine();

运行验证结果

针对你提供的test.txt测试文件,修复后输出完全符合预期:

Date Match,
Please enter file name: test.txt,
File exists!,
The date found is: 22 Jan,
The date found is: 27 December,
The date found is: 19 June,
The number of match is: 3.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:45:04