我正在使用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
答案 0 :(得分:3)
\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' ] ]
答案 1 :(得分:2)
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))
&#13;