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

寻求匹配多行数据的C# Regex正则表达式模式

匹配数据文件中所有特定格式行的C#正则表达式方案

目标行格式分析

先提炼所有示例行的共同结构特征:

  • 行首为1-2位数字(如69、70、80)
  • 后续是固定格式的小数(如1.0、2.0)
  • 接着是由字母、数字、连字符组成的标识符(连字符数量/位置不固定,支持ACS-PMM、PKS-EKC-FlYCTRK--Y、FREIGHT等所有示例样式)
  • 末尾是两个带千分位逗号或不带的两位小数金额(如2,110.28、31.75)

通用正则表达式

替换原有的死板匹配规则,写出能覆盖所有示例行的正则:

^(\d{1,2})\s(\d\.\d)\s([\w-]+)\s([\d,]+\.\d{2})\s([\d,]+\.\d{2})$

各部分规则说明

  • ^/$:锚定行首和行尾,确保匹配整行而非行内片段
  • (\d{1,2}):匹配1-2位数字的行号
  • (\d\.\d):匹配1.0/2.0这类固定格式的小数
  • ([\w-]+):匹配任意长度的标识符,支持字母、数字、连字符组合
  • ([\d,]+\.\d{2}):匹配带千分位或不带的两位小数金额,兼容两种格式

C# 代码实现示例

匹配所有符合格式的行

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

class Program
{
    static void Main()
    {
        string filePath = "your-data-file.txt";
        string regexPattern = @"^(\d{1,2})\s(\d\.\d)\s([\w-]+)\s([\d,]+\.\d{2})\s([\d,]+\.\d{2})$";
        Regex regex = new Regex(regexPattern, RegexOptions.Multiline);

        string fileContent = File.ReadAllText(filePath);
        MatchCollection matches = regex.Matches(fileContent);

        foreach (Match match in matches)
        {
            Console.WriteLine($"完整匹配行:{match.Value}");
            Console.WriteLine($"行号:{match.Groups[1].Value}");
            Console.WriteLine("---");
        }
    }
}
  • 启用RegexOptions.Multiline,让^/$作用于每行的首尾,而非整个文本的首尾

读取匹配行之间的内容

如果需要提取两个匹配行之间的内容,可按以下方式实现:

string[] lines = File.ReadAllLines(filePath);
List<int> matchLineIndices = new List<int>();

// 先记录所有匹配行的索引
for (int i = 0; i < lines.Length; i++)
{
    if (regex.IsMatch(lines[i]))
    {
        matchLineIndices.Add(i);
    }
}

// 遍历索引对,提取中间行
for (int i = 0; i < matchLineIndices.Count - 1; i++)
{
    int startIdx = matchLineIndices[i] + 1;
    int endIdx = matchLineIndices[i + 1];
    Console.WriteLine($"匹配行{matchLineIndices[i]}与{matchLineIndices[i+1]}之间的内容:");
    for (int j = startIdx; j < endIdx; j++)
    {
        Console.WriteLine(lines[j]);
    }
    Console.WriteLine("---");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:50:23