2017-06-01 3 views
0

基本的に私は、正規表現を使用していmatchTestは、変数の言葉を一致させるために、正規表現を保持し、一致して、この配列を取り込むこと、およびには、この配列["{test1、test2}"、 "test3"、 "{test4、test5}"から単語を抽出し、それらを1つの配列の中にまとめるためのエレガントな方法がありますか?

["{ test1, test2 }", "test3", "{test4, test5}"] 

から

["test1","test2","test3","test4","test5"] 

に配列を入れたいです配列を同じループに固定します。

while (regexMatches = matchTest.exec(sourceCode)) { 
    testArray.push(regexMatches[1].replace(/\W/g, " ").split(" ")); 
    testArray = [].concat(...testArray); 
    testArray = testArray.filter(testArray => testArray != ''); 
} 

私のやり方はうまくいきますが、かなり面倒です。これを改善する方法についての助けをいただければ幸いです。

答えて

3
var array = ["{ test1, test2 }", "test3", "{test4, test5}"]; 
var output = array.join(',').replace(/[^\w,]/g,'').split(','); 
+0

いい仕事です。私はそれを少し複雑に思っています.. – nnnnnn

+0

実際にこの/ [^ \ w、]/gは、 – alejandro

0

次のようにmatch

var string = '["{ test1, test2 }", "test3", "{test4, test5}"]'; 
 
var array = string.match(/\w+\d+/g); 
 
console.log(array);

3

私は.reduce()を使用したい置く必要があります。

var input = ["{ test1, test2 }", "test3", "{test4, test5}"] 
 

 
var output = input.reduce((acc, v) => { 
 
    acc.push(...v.replace(/[^\w,]/g,"").split(",")) 
 
    return acc 
 
}, []) 
 

 
console.log(output)

つまり、配列内の各項目に対して、まず単語またはカンマ以外のすべての文字を削除し、コンマで区切り、結果を出力配列にプッシュします。

関連する問題