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

Perl中处理重复分隔符(逗号)的split问题求助

问题:字符串分割与格式转换异常修正

输入字符串:

abc : {A=[2, 2, 2], B=x, C=[1, 1, 1, 1], D=1}

现有代码:

if ($_ =~ /^(\w+)\s+:\s+\{(\S+=.*)\}/)
{
  my $attr_struct = $1; 
  my $sub_attr_struct = $2;
  $sub_attr_struct =~ s/,\s+/,/g;
  my @sub_attr_struct_split = split(',',$sub_attr_struct);
  foreach my $attr (@sub_attr_struct_split)
   {
    print "$attr_struct".".$attr\n";  
   }
 }

期望输出:

abc.A=2:2:2
abc.B=x
abc.C=1:1:1:1 
abc.D=1

解决方案

原代码的核心问题是直接用逗号分割字符串,会误将数组内部的逗号当作键值对的分隔符,导致分割结果错误。以下是修正后的代码:

if ($_ =~ /^(\w+)\s+:\s+\{(.*?)\}/) {
    my $attr_struct = $1;
    my $sub_attr_struct = $2;
    
    # 将数组内部的", "替换为":",同时移除包裹的[]
    $sub_attr_struct =~ s/\[([^\]]+)\]/my $arr_content = $1; $arr_content =~ s/, /:/g; $arr_content/ge;
    
    # 仅分割数组外部的", "(即分隔不同键值对的逗号)
    my @sub_attrs = split(/,\s+(?![^\[]*\])/, $sub_attr_struct);
    
    foreach my $attr (@sub_attrs) {
        print "$attr_struct.$attr\n";
    }
}

修正要点

  1. 处理数组内部格式:使用带/e修饰符的正则,匹配[]包裹的数组内容,将其中的, 替换为:,同时直接移除[],一步到位符合输出要求。
  2. 精准分割键值对:利用正向否定断言(?![^\[]*\]),确保只分割不在[]范围内的, ,彻底避免破坏数组结构。
  3. 优化内容匹配:将原正则中(\S+=.*)改为(.*?),更稳妥地匹配{}内的所有内容,避免因开头非空白字符限制导致的匹配不全问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:52:45