Javascript解析INI文件內容的函數

.ini 是Initialization File的縮寫,即初始化文件,ini文件格式廣泛用於軟件的配置文件。

INI文件由節、鍵、值、註釋組成。

根據node.js版本的node-iniparser改寫瞭個Javascript函數來解析INI文件內容,傳入INI格式的字符串,返回一個json object。

[javascript] 
function parseINIString(data){ 
    var regex = { 
        section: /^\s*\[\s*([^\]]*)\s*\]\s*$/, 
        param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/, 
        comment: /^\s*;.*$/ 
    }; 
    var value = {}; 
    var lines = data.split(/\r\n|\r|\n/); 
    var section = null; 
    lines.forEach(function(line){ 
        if(regex.comment.test(line)){ 
            return; 
        }else if(regex.param.test(line)){ 
            var match = line.match(regex.param); 
            if(section){ 
                value[section][match[1]] = match[2]; 
            }else{ 
                value[match[1]] = match[2]; 
            } 
        }else if(regex.section.test(line)){ 
            var match = line.match(regex.section); 
            value[match[1]] = {}; 
            section = match[1]; 
        }else if(line.length == 0 && section){ 
            section = null; 
        }; 
    }); 
    return value; 

    function parseINIString(data){
        var regex = {
            section: /^\s*\[\s*([^\]]*)\s*\]\s*$/,
            param: /^\s*([\w\.\-\_]+)\s*=\s*(.*?)\s*$/,
            comment: /^\s*;.*$/
        };
        var value = {};
        var lines = data.split(/\r\n|\r|\n/);
        var section = null;
        lines.forEach(function(line){
            if(regex.comment.test(line)){
                return;
            }else if(regex.param.test(line)){
                var match = line.match(regex.param);
                if(section){
                    value[section][match[1]] = match[2];
                }else{
                    value[match[1]] = match[2];
                }
            }else if(regex.section.test(line)){
                var match = line.match(regex.section);
                value[match[1]] = {};
                section = match[1];
            }else if(line.length == 0 && section){
                section = null;
            };
        });
        return value;
    }
測試INI內容:

返回結果對象:

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *