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
  • 110,383
  • 23
  • 155
  • 178
Prashant Agrawal
  • 642
  • 8
  • 23
  • `/\[\[(\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,620
  • 1
  • 26
  • 38
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
  • 110,383
  • 23
  • 155
  • 178
1

If you need 2 separate matches use:

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

Regex101 Demo

Pedro Lobito
  • 85,689
  • 29
  • 230
  • 253
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
  • 22,595
  • 5
  • 50
  • 67