Regular Expressions: No Such Thing as Repeated Captures?

I've been trying to use regular expressions to grab a list of values from a function. The list has unknown length, but all the values are strings.

somefunc('asdf', 'zxcv', 'qwer');
asdf
zxvc
qwer

Now, the first reaction is to try something like this:

/^somefunc\((?:'([^']*)')*\)$/

In that regular expression, we match "somefunc(" first, then we have an non-capturing group denoted by "(?: ... )". The non-capturing group has a * at the end of it so it should repeat as often as needed and it does.

The problem is, when it repeats, it keeps overwriting the captured value. The actual resulting match looks like this:

qwer

I had a look at a concise little article about repeating and capturing but it doesn't really solve my problem. It looks like the only way to do this is to grab the contents of the function first, then do a smaller, global match for each argument.

Something like this:

var funcStr:String = "somefunc('asdf', 'zxvc', 'qwer')";
var matches:Array = funcStr.match(/^somefunc\((.*)\)$/);
 
var argStr:String = matches[1];
var matches2:Array = argStr.match(/'[^']*'/g);

Instead of that last regular expression, a split could be used as well. That is, unless you want to beef up the pattern to handle extreme cases such as 'asdf', 'zxvc\' ,', 'qwer'.

Me? I'm just surprised that the regular expression syntax doesn't provide a way to capture the values in one go. If you know of a way that I've missed, let me know!

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a Gravatar account, used to display your avatar.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • You can enable syntax highlighting of source code with the following tags: <code>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

About

Daniel McLaren

Daniel is a Flash and Flex developer specializing in the art of information visualization.

Latest from SketchyD

Latest Drawing from SketchyD

This is the most recent drawing from my mobile sketch blog, SketchyD.com.

Recent comments