tags:

views:

86

answers:

1

Hi all,

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

A: 

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!

Qtax
Thank you for taking a go at it - unfortunately I wasn't able to get it to work.
Matt
Can we have some more (real) examples of what you want to do here?
Qtax