0

Here is the string I have (as a string):

bytearray([source[, encoding[, errors]]])

Here is the data I want out of it:

arguments: [ { name: 'source', optional: true }, ... ]

Or put another way, I want the name of each argument and to know whether it is optional. The brackets denote whether it is optional.

I've made code to get just the arguments, and seen other examples for that, but not to get optional arguments.

Noah
  • 4,601
  • 9
  • 39
  • 52
  • 1
    What do you mean by _this is the data I want_? –  Dec 17 '15 at 19:29
  • 2
    This is impossible with regex. "Memory" is required to match closing braces to opening braces, and regex does not have sufficiently powerful memory (although it does have memory in a certain sense). This problem involves a *type-0 grammar*, and regex can only process *type-3 grammars* (https://en.wikipedia.org/wiki/Chomsky_hierarchy) – Gershom Maes Dec 17 '15 at 19:31
  • Wouldn't it be easier to list the arguments in JavaScript alone (without any regex, that is)? See here on SO for an example: http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function – Jan Dec 17 '15 at 19:44
  • I guess the naïve approach would be to use `\[[, ]*\w+` –  Dec 17 '15 at 19:45
  • @sin I want to know the name of the argument and whether it is optional. – Noah Dec 17 '15 at 20:06
  • 1
    Just find all `\[[, ]*(\w+)` .This matches only the optional ones. The name is in capture group 1. –  Dec 17 '15 at 20:17
  • @sin In this example, all the arguments are optional. They are all just nested. I don't really need to know if they're nested, just if they are optional. – Noah Dec 17 '15 at 21:14
  • @GershomMaes It doesn't need to be pure regex. Should I make a new question to clarify that or edit this one? – Noah Dec 17 '15 at 21:25

1 Answers1

0

Presuming that required arguments go before optional ones, the optionality can be determined by their immediate surroundings:

Argumente = []
'bytearray([source[, encoding[, errors]]])'
.replace(/\[[, ]*(\w+)|(\w+)(?=[[,)])/g,
         function(m, p1, p2) 
         { 
             Argumente.push({ name: p1||p2, optional: !p2 })
         })
console.log(Argumente)
Armali
  • 18,255
  • 14
  • 57
  • 171