[英]Regular expression to parse configuration file
即时通讯使用JavaScript读取文件
例子是
#########################
#####################
#sominfo
#some info
path = thisPath
file = thisFile.txt #this file may need a comment
我正在寻找一个正则表达式返回
[[path, thisPath],[file, thisFile.txt]]
要么
{path: thisPath,file: thisFile.txt} <-- which i'll probably have to do after the fact
\\S+
匹配一个或多个非空格字符。 (?! *#)
否定的前瞻断言开头没有字符#
。
var re = /^(?! *#)(\S+) *= *(\S+)/gm
var results = [];
while (m = re.exec(str)) {
var matches = [];
matches.push(m[1]);
matches.push(m[2]);
results.push(matches);
}
console.log(results) //=> [ [ 'path', 'thisPath' ], [ 'file', 'thisFile.txt' ] ]
str.replace
是您基于正则表达式进行分析的首选工具:
conf = "#########################\\n"+ "#sominfo\\n"+ "\\t\\t#some info = baz\\n"+ "\\n\\n#\\n\\n\\n"+ " path = thisPath\\n"+ "file \\t= thisFile.txt #this file may need a comment\\n"+ "foo=bar#comment\\n"+ " empty="; data = {} conf.replace(/^(?!\\s*#)\\s*(\\S+)\\s*=\\s*([^\\s#]*)/gm, function(_, key, val) { data[key] = val }); document.write(JSON.stringify(data))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.