2015-02-10 59 views
-1

IM正則表達式使用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

所有其他行開始以 「#」? – 2015-02-10 06:46:50

+0

'path'後''文件總是在線? – hwnd 2015-02-10 06:51:56

回答

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))

+0

非常感謝我花了一段時間對此做出結論,我不知道正則表達式是如何工作的 – cronicryo 2015-02-10 16:08:29

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

+0

或'^(?!#)(\ S +)* = *(。+?)(?= +#| $)' – 2015-02-10 06:52:19

+0

但是如果有其他線路行'something = something'。寫'(路徑|文件)'不是安全的' – nu11p01n73R 2015-02-10 06:53:48

+0

我認爲前面的=是路徑,'='後面是文件名。 – 2015-02-10 06:56:08

相關問題