Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract data between characters using regex?

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?

like image 239
Prashant Agrawal Avatar asked Apr 30 '16 10:04

Prashant Agrawal


3 Answers

Make it non-greedy as

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

Regex Demo

like image 106
rock321987 Avatar answered Oct 11 '22 07:10

rock321987


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>');
like image 44
Pranav C Balan Avatar answered Oct 11 '22 07:10

Pranav C Balan


If you need 2 separate matches use:

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

Regex101 Demo

like image 28
Pedro Lobito Avatar answered Oct 11 '22 08:10

Pedro Lobito