2015-04-14 37 views
4

有沒有辦法做到這一點?如果regexp不匹配,從數組中刪除元素

我有一個數組:

["file_1.jar", "file_2.jar","file_3.pom"] 

我想只保留「file_3.pom」,我想要做的是這樣的:

array.drop_while{|f| /.pom/.match(f)} 

但這樣一來我一直在數組中的所有東西,但「file_3.pom」有沒有辦法做一些像「not_match」?

我發現這些:

f !~ /.pom/ # => leaves all elements in array 

OR

f !~ /*.pom/ # => leaves all elements in array 

但這些都不是我期待的回報。

+1

你知道,在''/.pom .' /'匹配任何字符? – Stefan

+0

順便說一句,你的數組來自哪裏? – Stefan

回答

7

select怎麼樣?

selected = array.select { |f| /.pom/.match(f) } 
p selected 
# => ["file_3.pom"] 

希望有所幫助!

2

如果您只保留字符串女巫對regexp做出響應,您可以使用Ruby方法keep_if。 但是這種方法「摧毀」主陣列。

a = ["file_1.jar", "file_2.jar","file_3.pom"] 
a.keep_if{|file_name| /.pom/.match(file_name)} 
p a 
# => ["file_3.pom"] 
4

你的情況,你可以使用Enumerable#grep方法來獲取相匹配的模式元素的數組:

["file_1.jar", "file_2.jar", "file_3.pom"].grep(/\.pom\z/) 
# => ["file_3.pom"] 

正如你看到的,我也有小幅正則表達式修改爲實際僅匹配字符串,與.pom結束:

  • \.相匹配的文本點,沒有任何字符相匹配\
  • \z將模式錨定到字符串的末尾,沒有它,字符串中的任何位置都會匹配.pom

既然你正在尋找一個字符串,你也可避免正則表達式完全,例如使用方法String#end_with?Array#select

["file_1.jar", "file_2.jar", "file_3.pom"].select { |s| s.end_with?('.pom') } 
# => ["file_3.pom"]