首页 > 解决方案 > 我如何分解(拆分)给定的文本和分隔符字符串?

问题描述

我如何解析由两个块形成的字符串:

  1. { text }
  2. text

对于这两种情况,我都有两个正则表达式:

  1. \{[^\}]+\}
  2. *.

但不理解将它组合在一个正则表达式中。我曾考虑使用 or ( |) 运算符这样做:

/(\{[^\}]+\}|.*)/

但它不起作用。我该如何解决?

具体来说,如果我有一个字符串:

"{this is first text} this is second text {this is third text}"

使用preg_match_all我想要的东西:

Array
(
    [0] => Array
        (
            [0] => {this is first text}
            [1] => this is second text
            [2] => {this is third text}
        )

)

但我有结果:

Array
(
    [0] => Array
        (
            [0] => {this is first text}
            [1] => this is second text {this is third text}
            [2] => 
        )

)

非常感谢您的帮助。

标签: phpregex

解决方案


试试这个:

$str = "{this is first text} this is second text {} this is third text";
preg_match_all('/\s*(?:{})*\s*({.+?}|[^{}]+)/', $str, $matches);

print_r($matches[1]);

'/\s*(?:{})*\s*({.+?}|[^{}]+)/'意味着跳过空格和空大括号并在其中插入{}(里面也包括花括号)或除符号{和之外的所有内容}


推荐阅读