Search code examples
regexregex-group

Match function parameters with Regex


I created a Regex which allows to capture the parameters of a function.

The parameters are separated by the character ,

You can have the character , inside a parameter like 'lorem, impum'

The regex returns only the last match.

My Regex :

\s*(\'.+\'|\".+\"|[^,]+)?(?:\s*,?\s*(\'.+\'|\".+\"|[^,]+))*

function parametes

111111111111,'222222222',"33333333333333"

LInk to regex exemple : https://regex101.com/r/fdRJ92/2


Solution

  • var rx = /(?:^|,)\s*((('|").*?(?<!\\)(\3))|(\d?\.?\d+))/g;
    var str = `"21312\\'\\"3123\\"", 111111111111,'222222\\'222',"333333333,33333", 1234, .123, 0.3, '454'`;
    var match;
    while (match = rx.exec(str)) console.log(match[1]);
    

    Output

    "21312\'\"3123\""
    111111111111
    '222222\'222'
    "333333333,33333"
    1234
    .123
    0.3
    '454'