如何从字符串数组中提取特定的子字符串(基于正则表达式)
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);
我有一大堆字符串:
['{{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);