我正在为我正在处理的LESS项目制作一个分析工具,我在javascript中制定正确的正则表达式以匹配远程文件中的LESS变量时遇到问题包含较少的变量声明和注释。
以下是远程文件内容格式的示例:
// Little bit of commenting here
@foo: bar;
@bar: "http://google.com";
// Little bit more here...
@example-string: "some string";
@example-number: 10;
这个文件通过AJAX加载后,我的javascript将内容传递给我的getVars()函数,该函数应匹配at符号(@)到分号的所有内容:
function getVars(input) {
return input.match(/@.*;/gm);
}
这将返回一个包含变量声明的字符串数组,然后我可以将其映射到javascript对象。除了@bar变量值在字符串中的冒号之前停止之外,一切似乎都保持不变,如下所示:
@bar: "http
据我所知,冒号字符不是javascript正则表达式中的保留字符。任何人都可以帮忙修复我的正则表达式吗?
编辑:(使用更新的解决方案)
所以我犯了一个错误,感觉我的程序的另一部分对我的问题并不重要,但当然......那就是问题所在。在我的正则表达式返回一个匹配数组(虽然它很懒惰但工作正常)之后,它会在冒号字符处拆分每个项目,并将零和第一个索引分配为我的javascript对象中的键和值。我并没有注意到绝对网址中还有冒号的事实。
所以这里是我的新正则表达式和解决方案的其余部分:(被授予,它只是更大应用程序的一部分)
// Return array of variable declarations where 'input' is the raw file contents (which contains end of line characters: \n)
function getDeclarations(input) {
// matches @,
// then one or more of any word, hyphen or underscore,
// then zero or more whitespace,
// then zero or more of any character
// then a semicolon,
// then end the match at zero or more forward slashes followed by any character (comments)
return input.match(/@[\w-_]+:\s*.*;[\/.]*/gm);
}
// Map a single declaration to a key/value pair and return the object
function mapDeclaration(declaration) {
var parts = declaration.split(':'),
key = sanitizeVarKey(parts.shift()), // get just the first item
value = sanitizeVarValue(parts.join(':')); // join all the remaining items
return { key: value };
}
// Return variable key with at symbol removed
function sanitizeVarKey(input) {
return input.replace(/@/, '');
}
// Return variable value with leading white space and the semicolon removed
function sanitizeVarValue(input) {
return input.replace(/^\s+|;$/gm, '');
}