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!
Delicious
Digg
Reddit
Facebook
Google
Yahoo
Technorati

Comments
Post new comment