Working on a bit of an interesting project and I'm having a little trouble writing regex for this.
Using regex and Javascript, I want to split my input string into an array of "keys". Strings that have an invalid key should return 0 keys (null, empty array, whatever is fine).
The "spec"
<input string> => <matches>
# named keys
a => ['a']
b => ['b']
foo[bar] => ['foo', 'bar']
# numeric keys are ok too
a[0] => ['a', '0']
b[1] => ['b', '1']
# 'push' syntax is also valid
push[] => ['push', '']
hello[] => ['hello', '']
# complex!
complex[named][0][] => ['complex', 'named', '0', '']
Invalid examples
# named keys must start with [a-zA-Z]
_invalid => null
3foo[abc] => null
# named keys can include a number as long as they start with a letter
foo3valid[this_is_valid_2] => ['foo3valid', 'this_is_valid_2']
What I have so far
var regex = /^(?:\[?([a-zA-Z][a-zA-Z0-9_]*|[a-zA-Z0-9_]*)\]?)+$/g;
var keys = [];
myInput.replace(regex, function(match,capture,pos,source){
keys.push(capture);
});
console.log(myInput, keys);
How it fails
My regex is matching only the last "key" E.g.,
# should be ['a', 'b', 'c']
a[b][c] => ['c']