Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

just a quickie here..can anyone think of a regex to match the "array_name" portion of a an array/subscript reference like this (its a substitution, btw): $array_name[subscript] i tried something like /\$(\w+)(?!\[\w+\])/ but for some annoying reason, that matches everything but the last character of the array name (the first '\w' in the expression) and it also matches a normal variable like '$variable'..so its obvious im doing something horribly wrong. thanks

Replies are listed 'Best First'.
Re: regular expression matching array name
by Anonymous Monk on May 01, 2001 at 02:20 UTC
    /\$(\w+)(?:\[\w+\])/
Re: regular expression matching array name
by hdp (Beadle) on May 01, 2001 at 09:28 UTC
    /\$(\w+) *(?=\[)/ Given the example $foo[9], your regex first tries to match $foo, which fails because of the negative lookahead assertion (i.e. it is followed by [\w+]). Then it backtracks one character and tries again; $fo fits what it's looking for (\$(\w+), not followed by [\w+]), so that's what it matches.

    Your lookahead won't match the huge variety of Perl expressions that could be used to index an array, but that's okay, because all you need is to check for the opening [ anyway.

    It looks like you copied this code from somewhere else and don't really understand it; I can't think of any other reason you'd be using a negative lookahead there instead of a positive one.

    hdp.