filter a List according to multiple contains

23,380

Solution 1

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

Solution 2

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

e.g.

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

etc.

Solution 3

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.

Share:
23,380
Govind Singh
Author by

Govind Singh

Making stuff work... most of the time.

Updated on December 21, 2020

Comments

  • Govind Singh
    Govind Singh over 3 years

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