Regex to match top level delimiters in a multi dimensional string

前端 未结 3 1217
忘掉有多难
忘掉有多难 2020-12-22 07:13

I have a file that is structured in a large multidimensional structure, similar to json, but not close enough for me to use a json library.

The data looks something

3条回答
  •  Happy的楠姐
    2020-12-22 07:21

    Sure you can do this with regular expressions.

    preg_match_all(
        '/([^\s]+)\s*{((?:[^{}]*|(?R))*)}/',
        $yourStuff,
        $matches,
        PREG_SET_ORDER
    );
    

    This gives me the following in matches:

    [1]=>
    string(5) "alpha"
    [2]=>
    string(46) "
    beta {
        charlie;
    }
    delta;
    "
    

    and

    [1]=>
    string(7) "foxtrot"
    [2]=>
    string(22) "
    golf;
    hotel;
    "
    

    Breaking it down a little bit.

    ([^\s]+)                # non-whitespace (block name)
    \s*                     # whitespace (between name and block)
    {                       # literal brace
        (                   # begin capture
            (?:             # don't create another capture set
                [^{}]*      # everything not a brace
                |(?R)       # OR recurse
            )*              # none or more times
        )                   # end capture
    }                       # literal brace
    

    Just for your information, this works fine on n-deep levels of braces.

提交回复
热议问题