2016-04-30 87 views
5

我有一個字符串像[[user.system.first_name]][[user.custom.luid]] blah blah使用正則表達式提取字符之間的數據?

我想匹配user.system.first_nameuser.custom.luid

我建/\[\[(\S+)\]\]/但匹配user.system.first_name]][[user.custom.luid

任何想法,我做錯了?

+0

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

+1

寶[正則表達式提取方括號內的文本]的可能副本(http://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets) – 2016-05-18 23:13:21

回答

3

使其成爲非貪婪使用?匹配儘可能少的字符輸入成爲可能。那你的正則表達式將/\[\[(\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>');

1

如果您需要2個獨立的匹配使用:

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

Regex101 Demo

1

我覺得/[^[]+?(?=]])/g是一個快速的正則表達式。原來是在44完成步驟

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

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>") ;

相關問題