Tutorial :Regexp for handling recursive arguments



Question:

I'm a regexp novice, so I'm wondering what the regexp for the following:

function {function arg1, arg2}, arg3

I'm looking to be able to just select the top-level arguments: {function arg1, arg2} & arg3

Ideally the response would be using preg_match in PHP, but almost any regexp would work fine.

Thanks! Matt


Solution:1

PCRE/Perl regex, but I'm just guessing what you want (depending on the specs below):

/(?:function\s+|\G(?<!^),\s*)([^,{}]+|\{function\s+(?1)\s*(?:,\s*(?1)\s*)*})\s*/g  

Example Perl use:

test('function {function arg1, arg2}, arg3');  test('function foo, {function {function x}, y}, bar');    sub test{      print 'Matched: "', join '", "',          $_[0] =~          /(?:function\s+|\G(?<!^),\s*)          (              [^,{}]+              |              \{function\s+(?1)\s*(?:,\s*(?1)\s*)*}          )          \s*/gx;      print "\"\n";  }  

Output:

Matched: "{function arg1, arg2}", "arg3"  Matched: "foo", "{function {function x}, y}", "bar"  

Should work just fine in PHP, just escape where needed and use with preg_match_all.

Lots of questions about the specification tho:

  • Does the string you are matching on contain anything else than this?
  • Are there always two arguments?
  • Are arguments only one word?
  • Is "function" a keyword or a function name?

More (real) examples please!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »