7

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")
caffreyd
  • 1,151
  • 1
  • 17
  • 25
Govind Singh
  • 15,282
  • 14
  • 72
  • 106
  • 1
    Based on your need, it seems that you need to include the String that **ends with** (rather than contains) these extensions. Example: ```jpg.txt``` – Kevin Meredith Nov 11 '14 at 15:07

3 Answers3

16

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$$")))
Sergii Lagutin
  • 10,561
  • 1
  • 34
  • 43
4

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.

thund
  • 1,842
  • 2
  • 21
  • 31
3

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

e.g.

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

etc.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440