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

I have two lines in scala, and I want to find out if a large line ( needle ) contains a smaller line ( haystack ).

I found this with regular expressions and matches ( from this question ):

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

which (1) is roughly complicated for such a simple task, but more importantly, (2) does not work for me, because

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

returns

Boolean = false

+46
scala regex
Apr 12 2018-12-12T00:
source share
2 answers

If you want to do this with maximum efficiency, you may have to write it yourself (or find a good substring search 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 

This is not a regular expression search. You also do not use a regular expression (edit: because this code asks for an exact match with the entire string, and not for finding the appropriate substring), but this is another problem. If you want to count the number of matches, you can do something like

 scala> "needle".r.findAllIn("Finding needle in haystack").length res2: Int = 1 
+80
Apr 12 2018-12-12T00:
source share

Although I replied that I thought I also suggested this regex style

 scala> "I have a needle in my haystack" matches ".*needle.*" res10: Boolean = true 
+13
Apr 12 2018-12-12T00:
source share



All Articles