Reputation: 2243
val fields = Set("abc", "abcd", "abc per", "uio abcd", "yrabc", "entry", "peer")
def matchFields(param: String): Set[String] = ????
if I am providing input "abc"
to matchFields
method above; I am expecting the response as Set("abc", "abcd", "abc per", "uio abcd", "yrabc")
.
Can I know the implementation suggestions in scala with the help of regular expressions ?
Upvotes: 0
Views: 66
Reputation: 22374
No need for regular expressions here:
def matchFields(param: String): Set[String] = fields.filter(_.contains(param))
scala> matchFields("abc")
res0: Set[String] = Set(uio abcd, abc, abc per, yrabc, abcd)
contains
checks that one string is a substring of another, filter
filters out elements, that not match given predicate.
If you really really want regexps:
import scala.util.matching._
scala> def matchFields(R: Regex): Set[String] = fields.collect{case str@R() => str}
matchFields: (R: scala.util.matching.Regex)Set[String]
scala> matchFields(".*abc.*".r)
res5: Set[String] = Set(uio abcd, abc, abc per, yrabc, abcd)
Or:
scala> def matchFields(R: Regex): Set[String] = fields.flatMap(R.findFirstIn)
matchFields: (R: scala.util.matching.Regex)Set[String]
scala> matchFields(".*abc.*".r)
res7: Set[String] = Set(uio abcd, abc, abc per, yrabc, abcd)
.*
means 0 or more of any symbol. .r
creates Regex
from String
Upvotes: 1