【问题标题】:Extracting a randomly-chosen string within a main string: MATLAB在主字符串中提取随机选择的字符串:MATLAB
【发布时间】:2018-11-12 02:48:49
【问题描述】:

我正在使用的字符串类似于下面写的:

String_1='{2,2,1,1,{1,1,2,2,{1,2,{1,1,1,1,1}},2,2},{1,2,{1,2,2,2,2,2},2},{1,1},2,2,2,2,1,1,1,1,1}';

首先,我必须随机选择字符串中的一个数字。之后,我必须将所选数字中的字符串提取到第一个<strong>}</strong>,并用它创建另一个字符串(见图A) .注意,我们只从left移动到right

但是,如果所选数字中有<strong>n</strong>括号,我们必须跳过<strong>n</strong>closure 括号以到达我们正在寻找的右括号,如图 B 所示。

如果您有任何意见或建议,请告诉我。谢谢。

【问题讨论】:

    标签: regex string matlab random cell


    【解决方案1】:

    首先,找到12的位置,得到一个随机位置。

    inds = find(String_1 == '1' | String_1 == '2');
    random_number_pos = inds(randi(length(inds)));
    

    现在,我们可以利用栈的概念,找到第一个没有打开的}

    parentheses_opened = 0;
    start_ind = random_number_pos + 2; end_ind = 0;
    for ind = (random_number_pos + 2):length(String_1)
        if(String_1(ind) == '}' && parentheses_opened == 0)
            end_ind = ind - 1;
            break;
        elseif(String_1(ind) == '{')
            parentheses_opened = parentheses_opened + 1;
        elseif(String_1(ind) == '}')
            parentheses_opened = parentheses_opened - 1;
        end
    end
    
    String_2 = String_1(start_ind:end_ind);
    String_1((start_ind - 1):(end_ind + 1)) = [];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      相关资源
      最近更新 更多