在Node.js中通过正则表达式拆分数组

时间:2021-03-15 21:39:56

I'm using https://github.com/joyent/node-strsplit to split the text extracted from a file. I need to extract the data between double curly braces. Following will be some sample text in the file.

我正在使用https://github.com/joyent/node-strsplit来分割从文件中提取的文本。我需要在双花括号之间提取数据。以下是文件中的一些示例文本。

I am living in {{address||address of current property owner}} under the name {{name}} and my id (nic) will be {{nic||National Identity Number}})

我住在{{地址|当前财产所有者的地址}}下,名称为{{name}},我的身份(nic)将是{{nic || National Identity Number}})

Here, I want to extract the text inside double opening and closing curly braces. For example the ultimate array should be like, ['address||address of current property owner','name','nic||National Identity Number']

在这里,我想提取双开口和闭合花括号内的文本。例如,最终数组应该是,['地址||当前属性所有者的地址','名称','nic ||国家身份编号']

For this, I tried to use the following Regex patterns,

为此,我尝试使用以下正则表达式模式,

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

Following will my code.

以下是我的代码。

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

Please help me out for finalizing the approach. Cheers !!

请帮我确定最终方法。干杯!!

Updated:

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

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

1 个解决方案

#1


1  

You could do it with match() and strip the brackets:

您可以使用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)

#1


1  

You could do it with match() and strip the brackets:

您可以使用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)