5

I have a string something like [[user.system.first_name]][[user.custom.luid]] blah blah

I want to match user.system.first_name and user.custom.luid

I built /\[\[(\S+)\]\]/ but it is matching user.system.first_name]][[user.custom.luid.

Any idea where I am doing wrong?

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Prashant Agrawal
  • 660
  • 9
  • 24
  • `/\[\[(\S+?)\]\]/` – Pranav C Balan Apr 30 '16 at 10:56
  • 1
    Possible duplicate of [Regular expression to extract text between square brackets](http://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets) –  May 18 '16 at 23:13

4 Answers4

3

Make it non-greedy as

/\[\[(\S+?)\]\]/

Regex Demo

rock321987
  • 10,942
  • 1
  • 30
  • 43
3

Make it non-greedy using ? to match as few input characters as possible. That your regex will be /\[\[(\S+?)\]\]/

var str = '[[user.system.first_name]][[user.custom.luid]] blah blah'
var reg = /\[\[(\S+?)\]\]/g,
  match, res = [];

while (match = reg.exec(str))
  res.push(match[1]);

document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

If you need 2 separate matches use:

\[\[([^\]]*)\]\]

Regex101 Demo

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

I think /[^[]+?(?=]])/g is one fast regex. Turns out to be completed in 44 steps

[^[]+?(?=]])

Regular expression visualization

Debuggex Demo

Regex101

var s = "[[user.system.first_name]][[user.custom.luid]]",
    m = s.match(/[^[]+?(?=]])/g);
document.write("<pre>" + JSON.stringify(m,null,2) + "</pre>") ;
Redu
  • 25,060
  • 6
  • 56
  • 76