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

RegexStringScalaSubstringContains

Regex Problem Overview


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

Regex Solutions


Solution 1 - Regex

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

Solution 2 - Regex

Although answered I thought I would also offer this regex style

scala> "I have a needle in my haystack" matches ".*needle.*"
res10: Boolean = true

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKarel BílekView Question on Stackoverflow
Solution 1 - RegexRex KerrView Answer on Stackoverflow
Solution 2 - RegexNeil ChambersView Answer on Stackoverflow