正则表达式来解析配置文件

时间:2015-02-10 06:43:11

标签: javascript regex

我正在使用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

2 个答案:

答案 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' ] ]

Regex101 | Working Demo

答案 1 :(得分:2)

str.replace是您基于正则表达式的解析的首选工具:

&#13;
&#13;
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;
&#13;
&#13;