用于分隔值列表的正则表达式,其中的值可能包含分隔符

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

本文关键字:包含 分隔符 分隔 列表 正则表达式 用于      更新时间:2023-09-26

我试图捕捉具有以下形式的字符串中的模式:项目(选项),项目(选项)等。其中"item"是一个单词,选项可以包含任何字符。一个项可以没有选项,所以字符串可以是"item,item, item(options),item"。

到目前为止,我已经完成了这个:

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

但这并没有真正起作用。我希望能够捕获所有的结果,这样我就可以很容易地访问项目和选项。如有任何帮助,不胜感激!

编辑:恐怕这是不可能的:如果"选项"可以包含任何字符,如","或")",那么一个适当的正则表达式不能写,可以吗?

如何:

/
    '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