使用正则表达式在字符之间提取数据?

时间:2016-04-30 10:54:57

标签: javascript regex

我有一个类似[[user.system.first_name]][[user.custom.luid]] blah blah

的字符串

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

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

知道我做错了吗?

4 个答案:

答案 0 :(得分:3)

让它变得非贪婪

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

<强> Regex Demo

答案 1 :(得分: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>');

答案 2 :(得分:1)

如果您需要2个单独的比赛,请使用:

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

Regex101 Demo

答案 3 :(得分:1)

我认为/[^[]+?(?=]])/g是一个快速正则表达式。原来是44步完成

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

Regular expression visualization

Debuggex Demo

Regex101

&#13;
&#13;
var s = "[[user.system.first_name]][[user.custom.luid]]",
    m = s.match(/[^[]+?(?=]])/g);
document.write("<pre>" + JSON.stringify(m,null,2) + "</pre>") ;
&#13;
&#13;
&#13;