首页 > 解决方案 > 字符串到正则表达式的转换

问题描述

(name eq "xxxx" and user:(post.id eq 6 and post.post eq "testing") and data eq "Hello World!")

我有上面的字符串,我想通过 RegEx 过滤它以获得以下输出:

[
 [
   "name eq "xxxx"",
   "user" => [
       "post.id eq 6",
       "post.post eq testing",
   ],
   "data eq "Hello World!"",
 ],
 [
   "name",
   "user" => [
        post.id,
        post.post
   ],
   "data",
 ],
]

我尝试了以下正则表达式解决方案

/([\\w\\.]+)[\\s]+(?:eq)[\\s]+(?:"(?:[^"\\\\]|\\\\.)*"|\\d+(?:,\\d+)*(?:\\.\\d+(?:e\\d+)?)?|null)/i

并获得了价值

[
[
  "name eq "xxxx"",
  "post.id eq 6",
  "post.post eq "testing"",
],
[
  "name",
  "post.id",
  "post.post",
],
]

标签: phpregex

解决方案


试试这个,不过我会检查正则表达式

$input="(name eq \"xxxx\" and user:(post.id eq 6 and post.post eq \"testing\") and data eq \"Hello World!\")";

$inarr = [":(", ")","("];
$reparr   = [" and ", "", ""];
$input=str_replace($inarr, $reparr, $input);

$resultarr = explode(" and ", $input);

echo '[
      [
$resultarr[0]' . ',' .
      '"' . $resultarr[1] . '" => [' . 
   $resultarr[2] . ',' . 
   $resultarr[3] . ',' .
'],
   "' . $resultarr[4] . '",
 ],
 [
   "name",
   "user" => [
        post.id,
        post.post
   ],
   "data",
 ],
]';

推荐阅读