簡體   English   中英

用於解析配置文件的正則表達式

[英]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' ] ]

Regex101 | 工作演示

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM