Search code examples
javascriptregexseparator

regex for a list of separated values where values may contain the separator character


I'm trying to capture the patterns in a string having the following form : item(options),item(options), etc. where "item" is a word, and options can contain any characters. An item may have no options, so the string can be "item,item, item(options),item".

So far I've come with this:

/(\w+(\(.+\))*)(,(\w+(\(.+\))*))*/

But that does not really works. I want to be able to capture all the results, so that i can have an easy access to items and options. Any help would be appreciated !

EDIT: I'm afraid it's not possible : if "options" can contain any characters, like "," or ")", then a proper regex cannot be written, can it ?


Solution

  • How about:

    /
        \w+                 : one or more word characters
        (?:                 : start non capture group
            \([^)]+\)       : an open parens, some characters that are not parens, a close parens
        )?                  : this group is optional
        (?:                 : start non capture group
            ,               : a comma
            \w+
            (?:
                \([^)]+\)
            )?
        )*                  : 0 or more times the same pattern preceeded by a comma.
    /x                      : allow comments in regex