如果正则表达式不匹配,则从数组中删除元素

时间:2015-04-14 11:00:19

标签: ruby arrays regex

有办法做到这一点吗?

我有一个数组:

["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

但这些都没有回复我的期望。

3 个答案:

答案 0 :(得分:8)

select怎么样?

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

希望有所帮助!

答案 1 :(得分: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"]

答案 2 :(得分:2)

如果你想只保留Strings女巫对正则表达式的响应,那么你可以使用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"]