简体   繁体   English

Javascript正则表达式提取变量

[英]Javascript regex to extract variables

I have a string in Javascript that contains variables with the format ${var-name} . 我在Javascript中有一个字符串,其中包含格式${var-name}变量。 For example: 例如:

'This is a string with ${var1} and ${var2}'

I need to get these variables in an array: ['var1','var2'] . 我需要在数组中获取这些变量: ['var1','var2']

Is this possible with regex? 正则表达式可能吗?

Have a try with: 尝试一下:

/\$\{(\w+?)\}/

Running example, many thanks to @RGraham : 运行示例,非常感谢@RGraham:

var regex = new RegExp(/\$\{(\w+?)\}/g),
    text = "This is a string with ${var1} and ${var2} and {var3}",
    result,
    out = [];
while(result = regex.exec(text)) {
    out.push(result[1]);
}
console.log(out);

This regex - \\${([^\\s}]+)(?=}) - should work. 正则表达式 - \\${([^\\s}]+)(?=}) -应该可以正常工作。

Explanation: 说明:

  • \\${ - Match literal ${ \\${ -匹配文字${
  • ([^\\s}]+) - A capture group that will match 1 or more character that are not whitespace or literal } . ([^\\s}]+) -一个捕获组,将匹配一个或多个非空格或文字}字符。
  • (?=}) - A positive look-ahead that will check if we finally matched a literal } . (?=}) -积极的前瞻性,它将检查我们是否最终匹配了文字}

Here is sample code: 这是示例代码:

 var re = /\\${([^\\s}]+)(?=})/g; var str = 'This is a string with ${var1} and ${var2} and {var3}'; var arr = []; while ((m = re.exec(str)) !== null) { arr.push(m[1]); } alert(arr); 

var str = 'This is a string with ${var1} and ${var2}';

var re = /\$\{(\w+?)\}/g;
var arr = [];
var match;
while (match = re.exec(str)) {
  arr.push(match[1]);
}

console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM