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

正则表达式提取文本异常:C#中所有字段返回同一结果

正则匹配字段值异常问题解决

问题描述

需要从以下文本中提取对应字段的值:

[Name]
Jhon

[Age]
45

[MobileNumber]
1020304050

Billing address                     Delivery address 
India                               India

编写的C#正则提取代码运行后,所有字段输出结果均为India,与预期不符。

错误原因

  1. 变量未更新:匹配Billing address和Delivery address时,仅执行了正则匹配操作,但未将匹配结果赋值给value变量,导致输出的仍是之前最后一次赋值的结果。
  2. 正则表达式错误:原正则无法正确定位字段对应的值行,比如Billing address (.*)会匹配到该行中Billing address之后的所有内容(包括Delivery address及空格),而非下一行的地址值。

修复后的代码

static void Main(string[] args)
{
    string strContent =
        @"[Name]
          Jhon
          
          [Age]
          45
          
          [MobileNumber]
          1020304050
          
          Billing address                     Delivery address 
          GJ-India                                  MH-India"
    ;

    string value = string.Empty;

    // 匹配[Name]对应值
    var match = Regex.Match(strContent, @"\[Name\]\s*\n\s*(.*)", RegexOptions.Singleline);
    if (match.Success)
    {
        value = match.Groups[1].Value.Trim();
    }
    Console.WriteLine(value); // Jhon

    // 匹配[Age]对应值
    match = Regex.Match(strContent, @"\[Age\]\s*\n\s*(.*)", RegexOptions.Singleline);
    if (match.Success)
    {
        value = match.Groups[1].Value.Trim();
    }
    Console.WriteLine(value); // 45

    // 匹配[MobileNumber]对应值
    match = Regex.Match(strContent, @"\[MobileNumber\]\s*\n\s*(.*)", RegexOptions.Singleline);
    if (match.Success)
    {
        value = match.Groups[1].Value.Trim();
    }
    Console.WriteLine(value); // 1020304050

    // 匹配Billing address对应值
    match = Regex.Match(strContent, @"Billing address\s+Delivery address\s*\n\s*(.*?)\s+", RegexOptions.Singleline);
    if (match.Success)
    {
        value = match.Groups[1].Value.Trim();
    }
    Console.WriteLine(value); // GJ-India

    // 匹配Delivery address对应值
    match = Regex.Match(strContent, @"Billing address\s+Delivery address\s*\n\s*.+\s+(.*)", RegexOptions.Singleline);
    if (match.Success)
    {
        value = match.Groups[1].Value.Trim();
    }
    Console.WriteLine(value); // MH-India

    Console.ReadLine();
}

关键修复点

  • 变量赋值:每次匹配成功后,都将match.Groups[1].Value赋值给value,并通过Trim()去除多余空格。
  • 正则优化:
    • 对于[Name]这类字段,使用\[Name\]\s*\n\s*(.*)匹配字段行后的下一行内容,确保获取到对应的值。
    • 对于地址字段,先定位到地址标题行,再匹配下一行的对应内容:Billing address对应值取第一个非空格段,Delivery address对应值取第二个非空格段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:47:12