douyouming9180 2010-03-15 00:07
浏览 51
已采纳

正则表达式帮助 - 括号内的括号

I'm trying to develop a function that can sort through a string that looks like this:

Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air. 

What I intend to do is search the text recursively for {} patterns where there is no { or } inside the {}, so only the innermost sandwiched text is selected, where I will then run a php to array the contents and select one at random, repeating process until the whole string has been parsed, showing a complete sentence.

I just cannot wrap my head around regular expressions though.

Appreciate any help!

  • 写回答

5条回答 默认 最新

  • doufubian3479 2010-03-15 01:02
    关注

    Regular expressions don't deal well with recursive stuff, but PHP does:

    $str = 'Donny went to the {park|store|{beach with friends|beach alone}} so he could get a breath of fresh air.';
    
    echo parse_string($str), "
    ";
    
    function parse_string($string) {
        if ( preg_match('/\{([^{}]+)\}/', $string, $matches) ) {
            $inner_elements = explode('|', $matches[1]);
            $random_element = $inner_elements[array_rand($inner_elements)];
            $string = str_replace($matches[0], $random_element, $string);
            $string = parse_string($string);
        }
        return $string;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥750 关于一道数论方面的问题,求解答!(关键词-数学方法)
  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题