scala 根据多个包含过滤列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26842822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
filter a List according to multiple contains
提问by Govind Singh
I want to filter a List, and I only want to keep a string if the string contains .jpg,.jpegor .png:
我想过滤 a List,如果字符串包含.jpg,我只想保留一个字符串,.jpeg或者.png:
scala> var list = List[String]("a1.png","a2.amr","a3.png","a4.jpg","a5.jpeg","a6.mp4","a7.amr","a9.mov","a10.wmv")
list: List[String] = List(a1.png, a2.amr, a3.png, a4.jpg, a5.jpeg, a6.mp4, a7.amr, a9.mov, a10.wmv)
I am not finding that .containswill help me!
我没有发现这.contains对我有帮助!
Required output:
所需输出:
List("a1.png","a3.png","a4.jpg","a5.jpeg")
回答by Sergii Lagutin
Use filtermethod.
使用filter方法。
list.filter( name => name.contains(pattern1) || name.contains(pattern2) )
If you have undefined amount of extentions:
如果您有未定义的扩展数量:
val extensions = List("jpg", "png")
list.filter( p => extensions.exists(e => p.matches(s".*\.$e$$")))
回答by Brian Agnew
Why not use filter()with an appropriate function performing your selection/predicate?
为什么不使用filter()适当的函数来执行您的选择/谓词?
e.g.
例如
list.filter(x => x.endsWith(".jpg") || x.endsWith(".jpeg")
etc.
等等。
回答by thund
To select anything that contains one of an arbitrary number of extensions:
要选择包含任意数量的扩展名之一的任何内容:
list.filter(p => extensions.exists(e => p.contains(e)))
list.filter(p => extensions.exists(e => p.contains(e)))
Which is what @SergeyLagutin said above, but I thought I'd point out it doesn't need matches.
这就是@SergeyLagutin 上面所说的,但我想我会指出它不需要matches.

