RegEx to extract all matches from string using RegExp.exec

前端 未结 17 1489
-上瘾入骨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:27

    This isn't really going to help with your more complex issue but I'm posting this anyway because it is a simple solution for people that aren't doing a global search like you are.

    I've simplified the regex in the answer to be clearer (this is not a solution to your exact problem).

    var re = /^(.+?):"(.+)"$/
    var regExResult = re.exec('description:"aoeu"');
    var purifiedResult = purify_regex(regExResult);
    
    // We only want the group matches in the array
    function purify_regex(reResult){
    
      // Removes the Regex specific values and clones the array to prevent mutation
      let purifiedArray = [...reResult];
    
      // Removes the full match value at position 0
      purifiedArray.shift();
    
      // Returns a pure array without mutating the original regex result
      return purifiedArray;
    }
    
    // purifiedResult= ["description", "aoeu"]
    

    That looks more verbose than it is because of the comments, this is what it looks like without comments

    var re = /^(.+?):"(.+)"$/
    var regExResult = re.exec('description:"aoeu"');
    var purifiedResult = purify_regex(regExResult);
    
    function purify_regex(reResult){
      let purifiedArray = [...reResult];
      purifiedArray.shift();
      return purifiedArray;
    }
    

    Note that any groups that do not match will be listed in the array as undefined values.

    This solution uses the ES6 spread operator to purify the array of regex specific values. You will need to run your code through Babel if you want IE11 support.

提交回复
热议问题