RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1140
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:49

I\'m trying to parse the following kind of string:

[key:\"val\" key2:\"val2\"]

where there are arbitrary key:\"val\" pairs inside. I want t

17条回答
  •  迷失自我
    2020-11-22 03:05

    Here's a one line solution without a while loop.

    The order is preserved in the resulting list.

    The potential downsides are

    1. It clones the regex for every match.
    2. The result is in a different form than expected solutions. You'll need to process them one more time.
    let re = /\s*([^[:]+):\"([^"]+)"/g
    let str = '[description:"aoeu" uuid:"123sth"]'
    
    (str.match(re) || []).map(e => RegExp(re.source, re.flags).exec(e))
    
    
    [ [ 'description:"aoeu"',
        'description',
        'aoeu',
        index: 0,
        input: 'description:"aoeu"',
        groups: undefined ],
      [ ' uuid:"123sth"',
        'uuid',
        '123sth',
        index: 0,
        input: ' uuid:"123sth"',
        groups: undefined ] ]
    

提交回复
热议问题