2016-03-23 131 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]); 
     } 
    } 
}