2016-07-29 39 views
0

我使用https://github.com/joyent/node-strsplit拆分從文件中提取的文本。我需要在雙花括號之間提取數據。以下是文件中的一些示例文本。在Node.js中通過正則表達式拆分數組

我住在{當前業主的{地址||地址}}名稱{{名}}和本人身份證(NIC)下,將{{網卡||國民身份號碼}})

在這裏,我想提取雙開啓和關閉花括號內的文本。例如,最終陣列應該是這樣的,

對於這個[「名」,「NIC ||國民身份號碼」「||地址目前業主的地址」],我試圖用以下正則表達式模式,

/{{(.*?)}}/ 
/{{([^}]*)}}/ 
/\{{([^}]+)\}}/ 

以下將我的代碼。

var pattern = '/{{(.*?)}}/'; 
var arr=strsplit(sample_text, pattern); 

請幫我完成方法。乾杯!

更新時間:

var results = [], re = /{{([^}]+)}}/g, text; 

    while(item = re.exec(text)) { 
     results.push(item[1]); 
    } 
+0

爲什麼不使用'/{{(.*)}}? /g.exec(sample_text)'並在一個循環中獲取所有組1的值?見http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression –

回答

1

您可以用match()做到這一點,剝離括號:

var str = "I am living in {{address||address of current property owner}} under the name {{name}} and my id (nic) will be {{nic||National Identity Number}})"; 
 
var result = str.match(/{{.*?}}/g).map(function(x){return x.slice(2,-2)}); 
 
console.log(result)