1

I have been working with Discord.js and Node to a quick bot to look up something. I need a way to find all the occurrences that appear between two square brackers and store them in an array of strings. For now I'm using string-split() with some regex, but I am unsure of the regex to use.

I have tried using a few different ones, including /[^\[\[]+(?=\]\])/g and \[\[(.*?)\]\] - I dont mind having the actual brackets in the results, I can remove them manually with string.replace().

I am also working on a fallback with the normal string.split() and other string functions, not relying on regex, but I'm still curious about a possible regex version.

The result with the first regex is totally incorrect. For example, if I try "does [[this]] work [at all]?" the output is "[[]]" and "[at all]", when it really shouldn't take the "at all", but it shouls show the "[[this]]".

With the second regex I get somewhat closer, it gives back "this"(correct) and "[at all]" (again, it shouldn't take the "at all").

I don't mind having the brackets in the output, I can remove them manually myself, but I need to find all occurrences that are specifically between two brackets.

Rainfall
  • 21
  • 3

2 Answers2

0

Try this regex:

\[\[([^[\]]|(?R))*\]\]

What you are trying to do is called Matching Balanced Constructs. More info at the link.

Upon further testing, unfortunately JS does not support (?R) so this becomes far more difficult. You could use the XRegExp.matchRecursive addon from the XRegExp package.

And your expression \[\[(.*?)\]\] should work. Working example below.

var str = 'does [[this]] work [at all] with another double [[here]]?';

var result = str.match(/\[\[(.*?)\]\]/g);

var newDiv = document.createElement("div"); 
newDiv.innerHTML = result;
document.body.appendChild(newDiv);
Todd Chaffee
  • 6,754
  • 32
  • 41
  • with the ?R it just errors on execution, with "Invalid regular expression: Invalid group". removing ?R (so that it works on regex101.com) and testing with `does [[this]] work [please] [[cmon]] bot` it returns "does", "s", "[please]", "n", and "bot". – Rainfall Apr 27 '19 at 14:22
  • Ah, I just noticed JS doesn't support `(?R)`. I'll update the answer in a few minutes with a JS compatible solution. – Todd Chaffee Apr 27 '19 at 14:26
0

Try my solution

var str = "does [[this]] work [at all]?";
var regexp = /\[([a-z0-9\s]+)\]/ig;

var resultArray = str.match(regexp); 
resultArray = resultArray.map((item) => {
  return item.replace(/(\[|\])/g, "");
})

console.log(resultArray);
Alonad
  • 1,986
  • 19
  • 17