1

I'm trying to write a regex matching every dependency for a angular 1.5 class. This is what I got so far:

\$inject = \[('([\w]+)'([,]?[\s]?))*

This is what is a couple of test lines:

MyController.$inject = ['service1', 'service2', 'service3'];

MyController
    .$inject = [
        'service1',
        'service2',
        'service3',
    ];

This should be the result:

match = ['service1', 'service2', 'service3'];

But my regex above will only fetch the last item: service3, and I don't know why. Can anybody help?

Update

Got it working here: http://regexr.com/3e6c2

2
  • Consider using Esprima to make matching easier and far more accurate than a regex. Commented Sep 8, 2016 at 7:38
  • I did not know about this parser. Thanks, but I want this to be lightweight. Throwing every file I pick up through this parser, will exchange the trouble of interpret the actual code file for having to interpret a resultset from this parser. I'm not sure this will bring value to what I'm trying to achieve. Commented Sep 8, 2016 at 8:28

1 Answer 1

1

The reason is that when you quantify a capture group, only the last one is captured. You allow 0-unlimited repetitions of the capture group with the *. You'll have to capture them individually for it to work.

For an illustration, see this example at regex101. Here I've repeated the capture group three times instead of having a quantifier, and thus all three groups get capture.

I've also made some of the groups non-capturing ((?:...) to avoid noise in the groups.

This works if there's an finite number of groups. If the number of groups is unknown/to large you'll have to solve it programmatically.

Sign up to request clarification or add additional context in comments.

5 Comments

So for an unknown capture group I have to do this in two steps? There is no way of capturing the comma separated list between [ and ]; in one step?
Perhaps it would be better to do this instead then: \$inject = \[([a-zA-Z0-9_,'\s]+)\], thus capturing everything, and trim the result using javascript replace or something...
Not to my knowledge. But I'm a bit confused - do you already have the result in an array? Or is it a string you're parsing?
I'm parsing an entire javascript code file. Trying to retreive what injections the file has. This is for a node script I'm writing.
Ok. I think you should do it in two steps then - first find the data between the [] (e.g. /\[([^]]*)\]/) and then String.match the separate items in quotes /'[^']*'/g and you'll have them in an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.