What is the idiomatic scala way of finding, if a given string contains a given substring?

Karel Bílek picture Karel Bílek · Apr 12, 2012 · Viewed 79.4k times · Source

I have two strings in scala and I want to find out, if the bigger string (needle) contains a smaller string (haystack).

What I found is doing it with regexps and matches like this (from this question):

needle.r.pattern.matcher(haystack).matches

which is (1) grossly overcomplicated for such a simple problem, but more importantly, (2) doesn't work for me, because

"needle".r.pattern.matcher("Finding needle in haystack").matches

returns

Boolean = false

Answer

Rex Kerr picture Rex Kerr · Apr 12, 2012

If you want to do it with maximum efficiency, you may have to write it yourself (or find a good substring searching algorithm somewhere). If you just want it to work at all, then in Scala:

scala> "Finding needle in haystack" contains "needle"
res0: Boolean = true

scala> "Finding needle in haystack" indexOf "needle"
res1: Int = 8

These are not regex searches. You aren't using the regex match correctly either (edit: because that code asks for an exact match to the whole string, not to find a matching substring), but that's a different issue. If you want a count of the number of matches, you can do something like

scala> "needle".r.findAllIn("Finding needle in haystack").length
res2: Int = 1