如何让 json 嵌套在双方括号中?

How to get json nested in double square brackets?

这是我的样本:

dummy json: {json here: "asdas"}
[[table
  {json here: "asdas"}
]]
[[pre 
  {json here: "asdasx"}
]]
[[text {json here: "red"} ]]

我想要如下输出:

{json here: "asdas"}
{json here: "asdasx"}
{json here: "red"}

更新 json 字符串可能包含大括号。

我只想获取所有 json 个字符串,但我总是失败。
我试过使用 #\[\[(table|pre|text).+({.*?}).+\]\]#s 但我得到以下输出:

array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(126) "[[table
      {json here: "asdas"}
    ]]
    [[pre 
      {json here: "asdasx"}
    ]]
    [[text {json here: "red"} ]]"
  }
  [1]=>
  array(1) {
    [0]=>
    string(5) "table"
  }
  [2]=>
  array(1) {
    [0]=>
    string(18) "{json here: "red"}"
  }
}

顺便说一句,我正在使用 php 语法 preg_match_all 进行上述测试。

试试这个正则表达式:

#^\[\[(?:table|pre|text)\s+(\{.*?\})\s+\]\]$#m

删除了全局修饰符,因为您正在使用 preg_match_all。

以下应该有效:

(\[\[[(table|pre|text) ]*[\n ].*)({.*})

https://regex101.com/r/Yv67gb/1

这缩小样本以 [[table[[pre[[text 开始,然后 json 开始 { 结束 } 包含和介于两者之间的文本。

第 2 组将是我们的结果。

{json here: "asdas"}
{json here: "asdasx"}
{json here: "red"}

通过将您的正则表达式更改为以下内容,我能够让您的代码正常工作:

\[\[(?:table|pre|text)\s*(\{.*?\})\s*\]\]

请注意,如果您希望括号是字面意思,则需要对括号进行转义;你没有在你给我们看的正则表达式中这样做。

代码:

$userinfo = "[[table  {json here: \"asdas\"}]] [[pre {json here: \"asdasx\"}]] [[text {json here: \"red\"} ]]";
preg_match_all ("/\[\[(?:table|pre|text)\s*(\{.*?\})\s*\]\]/", $userinfo, $pat_array);
print $pat_array[1][0]." <br> ".$pat_array[1][1]." <br> ".$pat_array[1][2];

输出:

{json here: "asdas"} <br> {json here: "asdasx"} <br> {json here: "red"}

此处演示:

Rextester

这是最快最简单的模式:\[\[\S+\s+\K{.*} (Pattern Demo)

解释:

\[\[  #Match 2 opening square brackets
\S+   #Match 1 or more non-white-space characters
\s+   #Match 1 or more white-space characters
\K    #Start the fullstring match from this point (avoiding capture group)
{.*}  #Greedily match 0 or more non-line-terminating characters wrapped in curly brackets

*大括号在我的模式中不需要转义,因为它们不会被误认为量词。

鉴于我的代码中要遵循的输入值 ($in),我的模式仅需要 33 个步骤。 Tim 的模式需要 116 个步骤,并使用一个捕获组使 preg_match_all() 的输出数组大两倍。 inarilo 的模式需要 125 个步骤并使用捕获组。

如果有人特别想要一个捕获组,可以使用它:/\[\[\S+\s+({.*})/只需36步。

代码(PHP Demo):

$in='dummy json: {json here: "asdas"}
[[table
  {json here: "asd{as}"}
]]
[[pre 
  {json here: "asdasx"}
]]
[[text {json here: "red"} ]]';

echo implode('<br>',(preg_match_all('/\[\[\S+\s+\K{.*}/',$in,$out)?$out[0]:[]));

输出:

{json here: "asd{as}"}<br>{json here: "asdasx"}<br>{json here: "red"}