Govind Singh
Govind Singh

Reputation: 15490

filter a List according to multiple contains

I want to filter a List, and I only want to keep a string if the string contains .jpg,.jpeg or .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 .contains will help me!

Required output:

List("a1.png","a3.png","a4.jpg","a5.jpeg")

Upvotes: 7

Views: 29163

Answers (3)

thund
thund

Reputation: 1953

To select anything that contains one of an arbitrary number of extensions:

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.

Upvotes: 4

Sergii Lagutin
Sergii Lagutin

Reputation: 10671

Use filter method.

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$$")))

Upvotes: 16

Brian Agnew
Brian Agnew

Reputation: 272287

Why not use filter() with an appropriate function performing your selection/predicate?

e.g.

list.filter(x => x.endsWith(".jpg") || x.endsWith(".jpeg")

etc.

Upvotes: 3

Related Questions