2016-03-23 214 views
0

我有這個數組的數組,我想通過它循環,給我每一個字,但從「@」,標點符號和標籤剝離。然而,我的正則表達式是完全從數組中刪除一些單詞,我不知道爲什麼。正則表達式的JavaScript不工作

[ [ '@AIMEEE94x', 
     '@Arsenal_Geek', 
     '@Charlottegshore', 
     'shut', 
     'it', 
     'ha' ], 
    [ '"You', 
     'learn', 
     'so', 
     'much', 
     '@MesutOzil1088', 
     'and', 
     '@Alexis_Sanchez"', 
     '-', 
     '@alexiwobi:' ] ] 


    var regex = /\w+/g; 
    var listsb = []; 
    for (i = 0 ; i < tweetsA.length; i++) { 
     for(j = 0; j < tweetsA[i].length; j++){ 

      if (regex.test(tweetsA[i][j])== true){ 
       listsb = listsb.concat(tweetsA[i][j]) 
      }                         

     } 
    } 
    console.log(listsb); 

回答

1

如果你想刪除所有其他字符,那麼只是對正則表達式的檢查是不夠的。你需要找到匹配的確切模式。這是通過使用字符串的match功能以JavaScript

var str = "@Alexis_Sanchez"; 
var regex = /\w+/g; 
var match = str.match(regex); //match = ['Alexis_Sanchez'] 
var str2 = "@alexwobi:"; 
var match2 = str2.match(regex); //match2 = ['alexwobi'] 

匹配的該值(如果存在匹配)應列表陣列內被推動完成。

\ w元字符相當於[A-Za-z0-9_]。所以它不會爲你刪除下劃線。另外,如果在單詞中間有一個非\ w字符,則會在匹配數組中獲得兩個元素。他們都需要被追加,然後推入你的列表中。

0

爲此,使用String.match()會不會更容易?像這樣:

var regex = /\w+/g; 
var listsb = []; 
for (i = 0 ; i < tweetsA.length; i++) { 
    for(j = 0; j < tweetsA[i].length; j++){ 
    listb.push(tweetsA[i][j].match(regex)); //Will give you string stripped with regex characters.                       
    } 
} 
0

根據您評論中的更新提供的新答案。該版本遍歷所有找到的匹配並將它們添加到列表中。

var regex = /\w+/g; 
var listsb = []; 
for (i = 0 ; i < tweetsA.length; i++) { 
    for(j = 0; j < tweetsA[i].length; j++) { 
     while((m = regex.exec(tweetsA[i][j])) != null) { 
      listsb = listsb.concat(m[0]); 
     } 
    } 
}