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

如何用RegEx.Split解析特定格式字符串生成目标字符串数组?

问题描述

输入字符串:

string input = "{A.0a,100,0002_VL}{=}{A.0a,0400,0001_VL}{+}{A.0a,0410,0002_VL}{+}{A.0a,0420,0003_VL}"

期望得到的字符串数组:

string[] output 

output[0] = "A.0a,100,0002_VL"
output[1] = "="
output[2] = "A.0a,0400,0001_VL"
output[3] = "+"
output[4] = "A.0a,0410,0002_VL"
output[5] = "+"
output[6] = "A.0a,0420,0003_VL"

希望使用RegEx.Split函数实现,但不确定合适的正则表达式模式,请求技术帮助。

解决方案

完全可以用RegEx.Split实现,核心思路是通过零宽断言匹配元素分隔的位置,拆分后再做简单过滤处理。

推荐正则表达式模式

(?<=})|(?={)

这个模式利用零宽断言定位拆分点:

  • (?<=}):匹配}字符之后的位置
  • (?={):匹配{字符之前的位置

完整C#代码示例

using System;
using System.Text.RegularExpressions;
using System.Linq;

class Program
{
    static void Main()
    {
        string input = "{A.0a,100,0002_VL}{=}{A.0a,0400,0001_VL}{+}{A.0a,0410,0002_VL}{+}{A.0a,0420,0003_VL}";
        // 按断言位置拆分
        string[] splitParts = Regex.Split(input, @"(?<=})|(?={)");
        
        // 过滤空字符串,同时去除每个元素的首尾{}
        string[] output = splitParts
            .Where(s => !string.IsNullOrEmpty(s))
            .Select(s => s.Trim('{', '}'))
            .ToArray();
        
        // 验证输出
        for (int i = 0; i < output.Length; i++)
        {
            Console.WriteLine($"output[{i}] = \"{output[i]}\"");
        }
    }
}

补充说明

这种零宽断言的方式通用性很强,不管包裹的是复杂元素还是单个运算符,都能准确定位拆分点,后续的过滤和去括号操作也简单直观,避免了复杂的捕获组逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:27:30