0
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 ?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.