Ken Hui
Ken Hui

Reputation: 39

How can I capture word by Regex

I would like to capture the array key from a string.

Here are my words: message[0][generic][0][elements][0][default_action][url]...

I want to capture the array keys after message[0][generic][0][elements][0], and the expected results are default_action and url etc.

I have tried following patterns but not work.

  1. message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\]): it captures default_action only;
  2. \[(\w+)\]: it captures all array keys, but includes 0, generic, elements...

Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]?

Upvotes: 0

Views: 125

Answers (3)

SLePort
SLePort

Reputation: 15461

To extract any number of keys and reverse the order of the elements in resulting array:

str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
  .map(function(s) { return s.replace(/[\[\]]/g, "") })
  .reverse();
console.log(res);

Upvotes: 0

Jan Ciołek
Jan Ciołek

Reputation: 1816

You can replace unwanted part of a string,and then get all other keys.

var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';

var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/

var answer = string.replace(regexp,'').match(/[^\[\]]+/g)

console.log(answer);

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The solution using String.prototype.split() and Array.prototype.slice() functions:

var s = 'message[0][generic][0][elements][0][default_action][url]...',
    result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
    
console.log(result);

Upvotes: 0

Related Questions