繁体   English   中英

如何从字符串数组中提取特定的子字符串(基于正则表达式)

[英]How to extract a specific substring (based on regex) from an array of strings

我有一大串字符串:

['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false'...]

我想过滤数组并将每个{{Wanted Value}}子字符串提取到一个新数组中。 如果数组中的项目包含 2 个或更多这些子字符串,我希望将它们中的每一个作为单独的项目。 所以上述数组的结果是:

['{{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}']

我编写了我想使用的正则表达式,但不确定如何正确编写过滤器函数:

match(/\{\{(.+?)\}\}/)[0]

谢谢

你可以试试这个方法

  • flatMap是收集所有匹配的字符串
  • filter是去除空结果

 const data =['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false'] const result = data.flatMap(stringData => stringData.match(/\{\{(.+?)\}\}/g)).filter(stringData => stringData); console.log(result)

这是一个使用reduce和字符串match函数来过滤结果的代码

 let r = ['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}}', 'unwanted','{{Wanted Value}}', 'false']; const result = r.reduce((accumulator, current) => { return current.match(/\{\{(.+?)\}\}/)? accumulator.concat(current): accumulator; }, []); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM